Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the problem of react-router browserHistory refreshing page 404

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the react-router browserHistory refresh page 404 how to solve the relevant knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that everyone after reading this react-router browserHistory refresh page 404 how to solve the article will have a harvest, let's take a look.

Background

When using webpack-dev-server as a local development server, normally, you only need to simply use the webpack-dev-server instruction to start, but when the project is in the following two situations, nested routes and asynchronous load routes are often required:

We use a routing library like react-router to build single-page application routing

Use the html-webpack-plugin plug-in to dynamically inject js-loaded tags into html documents

At this time, accessing localhost:9090 can load files such as pages and js normally, but when we need to access secondary or even tertiary routing or refresh pages, such as localhost:9090/posts/92, two situations may occur:

Failed to load page, return Cannot Get (404)

The service responded, but the html file outputted by webpack processing was not returned, so that the js resource could not be loaded. The second case is shown in the figure:

So how do we deal with the normal access to each page routing? The blogger traces the source and finds the document configuration to solve the problem. This article is a summary of the whole problem-solving process.

Analyze the problem

After finding the problem, we should begin to analyze and solve the problem. We judge that the problem is generally caused by two reasons:

React-router front-end route configuration

Webpack-dev-server service configuration

React-router

Because the front-end route is easier to determine the problem, easier to analyze, and more familiar with react-router, first query the relevant configuration information of the react-router routing library, and find that when using browserHistory mentioned in the document, it will create a real URL, and there is no problem in dealing with the initial / request, but after the jump route, when refreshing the page or directly accessing the URL, you will find that it cannot be correctly corresponding. For more information, see the reference documentation. Several server configuration solutions are also provided in the documentation:

Node

Const express = require ('express') const path = require (' path') const port = process.env.PORT | | 8080const app = express () / / commonly used to load static resources app.use (express.static (_ _ dirname +'/ public')) / / handle any routeapp.get ('*', function (request, response) {response.sendFile (path.resolve (_ _ dirname, 'public')) in index.html that contains a script tag / / in your application JavaScript file 'index.html')}) app.listen (port) console.log ("server started on port" + port)

When using Node as a service, you need to use the wildcard * to listen for all requests and return the target html document (the html that references the js resource).

Nginx

If you are using a nginx server, only use the try_files directive:

Server {... Location / {try_files $uri / index.html}}

Apache

If you use an Apache server, you need to create an .htaccess file in the root directory of the project, which contains the following:

RewriteBase / RewriteRule ^ index\ .html $- [L] RewriteCond% {REQUEST_FILENAME}!-fRewriteCond% {REQUEST_FILENAME}!-dRewriteRule. / index.html [L]

The following are all for the configuration of the server, but unfortunately we have not introduced the relevant server yet, only using the built-in service of webpack-dev-server, but we have found the problem, that is, the routing request does not match the returned html document, so it is time to go to the webpack-dev-server document to find a solution.

Webpack-dev-server

Here, I have to complain about the official webpack-dev-server document. The blogger has read it several times before he can see the problem clearly. There are also two situations:

Output.publicPath has not been modified, that is, there is no declared value in the webpack configuration file, which is the default.

Set output.publicPath to a custom value

Click here to view the document

Default

By default, the output.publicPath value is not modified, you just need to set the historyApiFallback configuration for webpack-dev-server:

DevServer: {historyApiFallback: true}

If you are using the HTML5 history API you probably need to serve your index.html in place of 404 responses, which can be done by setting historyApiFallback: true

If your application uses HTML5 history API, you may need to use index.html to respond to 404 or question requests, just set g historyApiFallback: true

Custom value

However, if you have modified output.publicPath in your Webpack configuration, you need to specify the URL to redirect to. This is done using the historyApiFallback.index option

If you modify the output.publicPath value in the webpack configuration file, you need to declare the request redirection and configure the historyApiFallback.index value.

/ / output.publicPath:'/ assets/'historyApiFallback: {index:'/ assets/'}

Proxy

Found that using the above methods can not completely solve my problem, there will always be abnormal response to routing requests, so bloggers continue to find a better solution:

Click here to view the document

The proxy can be optionally bypassed based on the return from a function. The function can inspect the HTTP request, response, and any given proxy options. It must return either false or a URL path that will be served instead of continuing to proxy the request.

The proxy provides different processing for different requests through the return value of the function. The function parameters receive the HTTP request and response body, as well as the proxy configuration object. This function must return a false or URL path to indicate how to continue processing the request. When URL is returned, the source request will be proxied to the URL path request.

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';}

As configured above, you can listen to requests at the beginning of / under the https://api.example.com domain (equivalent to all requests), and then determine whether the accept field in the request header contains html. If so, the proxy request is sent to / index.html, and then the index.html document is returned to the browser.

Solve the problem

Based on the above solution, the blogger uses webpack-dev-server Proxy proxy to solve the problem because the output.publicPath is changed to / assets/, in the webpack configuration:

Const PUBLICPATH ='/ assets/'...proxy: {'/': {bypass: function (req, res, proxyOptions) {console.log ('Skipping proxy for browser request.') Return `${PUBLICPATH} / index.html`}

Listen to all front-end routes and directly return ${PUBLICPATH} / index.html,PUBLICPATH, which is the set output.publicPath value.

In addition, bloggers always make a habitual declaration, although the expected access effect can be achieved without setting this attribute:

HistoryApiFallback: true's article on "how to solve react-router browserHistory Refresh Page 404" ends here. Thank you for reading! I believe you all have a certain understanding of the knowledge of "react-router browserHistory refresh page 404". If you still want to learn more knowledge, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report