HashRouter react route using the difference and the BrowserRouter -Content Security Policy img-src 404 (Not found)

Stepped pit experience

Yesterday saw articles about the react-route, saying BrowserRouter better than HashRouter number, react also recommended BrowserRouter, after all, in their own front-end side, is a white, others say what I did well, so I put route changed from HashRouter BrowserRouter
then today has been moderate over the tragedy, when routing mode using browserHistory, click on each navigation can display the correct page, once the browser refresh the page is displayed can not GET

then a variety of Baidu, a variety of debugging has been no transfer through, there are even a few hours, to reinvent the wheel, after all, nothing is redone can not be resolved, but this cost too much, they have to copy the code again, possibly even to the last, this problem still occurs, until the time 22:00 bath, suddenly figured out, is not due to the route change BrowserRouter from HashRouter cause users to access the resource does not exist, so that the Content Security Policy do? Bath quickly change back, and sure enough the line, bath time is really the most relaxing, most sober head.

Cause Analysis (Baidu to find)

React-Router is based on history, a common history routing program has three forms, namely:

  • hashHistory
    • hashHistory use the URL hash (#) to create part of the route, for example, user access http://www.example.com/, will actually see is http://www.example.com/#/.
  • browserHistory
    • browserHistory 是使用 React-Router 的应用推荐的 history方案。它使用浏览器中的 History API 用于处理 URL,创建一个像example.com/list/123这样真实的 URL
    • 当刷新页面时,浏览器会向服务器请求,服务器实际会去找根目录下对应的文件,发现找不到,因为实际上我们的服务器并没有这样的 物理路径/文件 或没有配置处理这个路由,所有内容都是通过React-Router去渲染React组件,自然会报404错误。
  • createMemoryHistory
    • Memory history 不会在地址栏被操作或读取。这就解释了我们是如何实现服务器渲染的。同时它也非常适合测试和其他的渲染环境(像 React Native )。和另外两种history的一点不同是你必须创建它,这种方式便于测试。

两种解决方法

  • 使用hashHistory,不用做额外处理
  • 使用browserHistory,服务器需要进行相关路由配置
    方法见这里

Guess you like

Origin www.cnblogs.com/phonecom/p/11223266.html
Recommended