About the use of BrowserRouter and HashRouter in React deployment server

foreword

In the new version of React, the Router component is split into BrowserRouter, HashRouter, and createMemoryHistory. Although it is more standardized, it also brings more problems.

question

Originally, I used BrowserRouter for routing jump at the beginning of the project, and there was no problem at all in the development environment. But when it is deployed on the server, only the homepage is loaded normally, and when the route is redirected, the route cannot be found and 404 is reported.

Introduction to Browserhistory and Hashhistory

BrowserRouter uses Browserhistory and HashRouter uses Hashhistory

1.Browser history

is the recommended history for apps using React Router. It uses the History API in the browser for processing URLs, creating a real URL like example.com/some/path. Whenever a routing jump is made, he will send the url to the server for request.

2.Hash history

Use the hash (#) part of the URL to create routes like example.com/#/some/path. The main principle is to listen to the browser hashchange event triggered by the change of the URL path identifier after #, and then obtain the current path identifier by obtaining location.hash, and then perform some routing jump operations. He will not send a request to the server

So the reason for 404 is that in browserHistory mode, the URL is the resource path pointing to the real URL. When accessing the website through the real URL, since the path is the real path pointing to the server, but there are no related resources under this path, so The resource accessed by the user does not exist.

reason

After synthesizing most of the blogs on the Internet, it is concluded that BrowserRouter is no problem in the development environment, and the configuration of webpack has already been processed. However, in the server environment, the real path of the server is directly accessed, but this path is not available, and a 404 problem occurs.

Solution

1. Use HashRouter:

Change the BrowserRouter in the code to HashRouter, access it through '#', so that the path will not be sent to the server, and the normal jump will be realized.

2.BrowserRouter

Method 1 can be done if it is a personal project, but in actual production and life, it is not recommended to use '#' for routing jumps. The real path is more standardized for routing jumps, and the official React is also the main recommended use BrowserRouter.

Therefore, we use nginx configuration to return the routes that cannot be found to index.html, so that after refreshing, using the browser cache, js will control which page should be displayed according to the route. The configuration is as follows:

location / {
	   try_files $uri /index.html;
 }

References:
http://react-guide.github.io/react-router-cn/docs/guides/basics/Histories.html

Guess you like

Origin blog.csdn.net/weixin_43896829/article/details/110074446