Refresh the browser with react-router, the page 404 problem is solved

First of all, let's find the problem first, and then solve the problem. Don't think I'm long-winded. First, let's talk about the three modes of react routing history.

history configuration

React Router is built on history. In short, a history knows how to listen for changes in the browser's address bar, parse the URL into a location object, and then use it to match the route to the router, and finally render the corresponding component correctly.
There are three forms of commonly used history, but you can also implement custom history using React Router.

  • createHashHistory

  • createBrowserHistory

  • createMemoryHistory

What is the difference between these three:

createHashHistory

This is a default history you will get if you don't specify a history. It uses the hash (#) part of the URL to create a route like http://mtui.mtsee.com/#/help .
This browser supports ie8+, but it is not recommended because it is a hash value.

createBrowserHistory

Browser history is the recommended history for creating browser applications by React Router. It was created in the browser to handle URLs using the History API, creating a real URL like http://mtui.mtsee.com/help .

Memoryhistory

The address bar will not be manipulated or read.

So here comes the problem~

Use reateHashHistory, because the #hash method used here, the real url has not changed. The only change is the hash value, so we can directly access the address http://mtui.mtsee.com/#/help  next time , but this mode is not conducive to SEO and is not recommended.

When using createBrowserHistory, because the History API is used to process the url, the real url has changed. When we refresh the browser, the internal has been reset. We will visit the address http://mtui.mtsee.com/help next time . At that time, the previous history has been updated, which is equivalent to going directly to the server to request this url. Of course, we are using front-end routing. The server must not know what this is, so it returns the 404 page.

This needs to be set on the server. There is very little related information on the Internet, and I found an article: nginx-for-react  , but I am using Apache and don't want to install other servers, so I thought about it myself and decided to try redirecting 404. So I thought of a simple method: modify the htaccess file .

htaccess add a sentence: ErrorDocument 404 /index.html 

Actually got it~ The problem is solved~

What about 404 pages? So rude, does the boss know? Let’s talk about it, set htaceess to specify the url redirection, and fiddle with it yourself. Anyway, you can redirect to /index.html~





{{o.name}}
{{m.name}}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324125106&siteId=291194637