react-router的browserHistory/react-router-dom的BrowserRouter刷新页面404问题解决

前端解决:

  • '/' 表示把所有的url都发给代理https://api.example.com
  • bypass 表示不需要发给发给代理服务器的条件

  如下配置,可以监听https://api.example.com域下的/开头的请求(等效于所有请求),然后判断请求头中accept字段是否包含html,若包含,则代理请求至/index.html,随后将返回index.html文档至浏览器。

proxy: {
  '/': {
    target: 'https://api.example.com',
    secure: false,
    bypass: function(req, res, proxyOptions) {
      if (req.headers.accept.indexOf('html') !== -1) {
        console.log('Skipping proxy for browser request.');
        return '/index.html';
      }
    }
  }
}

django后端解决

对于所有后端不存在的url直接返回index.html文档给浏览器

handler404 = view.page_not_found


# 强制刷新前端功能
def page_not_found(request, exception, template_name='index.html'):
    return render(request, template_name)

参考:

http://blog.codingplayboy.com/2017/12/26/react-router-browserhistory-404/