To expand on Phi Nguyen's answer the reason hashHistory works and browserHistory fails is because hashHistory is sort of a 'hack' or workaround to allow your app to manipulate the URL without the browser noticing and sending a GET
request to your server. Essentially everything after the Hash is ignored.
browserHistory is generally preferred because it looks better but you no longer get the hash workaround and you need other means of preventing your browser from trying to send requests to your server. IF you are using webpack there is a simple way to essentially make all requests fallback to a single request. For example:
GET
to http://localhost:8080/ AND a GET
to http://localhost:8080/about would both fallback to http://localhost:8080/ and react-router would deal with the /about. (this is the reason you are able to navigate to /about fine, but if you refresh you get a 404
error, you're sending a GET
to /about which doesn't exist on your server)
To do this you need to implement a webpack feature called history api fallback. There's two ways of doing that.
From the react-router docs / tutorial you can setup your start
script to look like this:
"start": "webpack-dev-server --inline --content-base . --history-api-fallback"
Where the --history-api-fallback is the important piece for anyone with this error.
OR you can change your webpack.config.js
file to look handle this on your dev server.
devServer: {
historyApiFallback: true,
...other stuff..
},
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…