search
HomeWeb Front-endJS TutorialHow to solve react-router browserHistory refresh page 404 problem

When using React to develop a new project, when refreshing the page and directly accessing the secondary or tertiary routing, the access fails and a 404 or resource loading exception occurs. This article analyzes this problem and summarizes the solution. This article mainly introduces the solution to the 404 problem of react-router browserHistory refresh page. It is of great practical value. Friends in need can refer to it. I hope it can help everyone.

Background

When using webpack-dev-server as a local development server, under normal circumstances, you only need to simply use the webpack-dev-server command to start it. However, when the project is in the following two situations, nested routing and asynchronous loading routing are often required:

  1. We use a routing library such as react-router to build single-page application routing;

  2. Use the html-webpack-plugin plug-in to dynamically inject the <script> tag of loaded js into the html document; </script>

At this time, visit localhost:9090 Pages and js and other files can be loaded normally, but when we need to access the second-level or even third-level routing or refresh the page, such as localhost:9090/posts/92, ​​two situations may occur:

  1. Page loading failed and Cannot Get (404) was returned;

  2. The service responded, but the html file output by webpack processing was not returned, resulting in the inability to load js resources. Second This situation is as shown in the figure:

So how do we deal with it so that we can access it normally and route each page? The blogger traced the source and solved the problem after searching for document configuration. This article is a summary of the entire problem-solving process.

Analyze the problem

After discovering the problem, we will start to analyze and solve the problem. We judge that this problem is generally caused by two reasons :

  1. react-router front-end configuration;

  2. webpack-dev-server service configuration;

react-router

Because front-end routing is easier to identify problems, more convenient for analysis, and more familiar with react-router, so first query the react-router routing library For related configuration information, I found that the document mentioned that when using browserHistory, a real URL will be created and there will be no problem processing the initial/request. However, after jumping to the route, refreshing the page or directly accessing the URL, you will find that it cannot respond correctly. More For information, check the reference document. The document also provides several server configuration solutions:

Node


const express = require(&#39;express&#39;)
const path = require(&#39;path&#39;)
const port = process.env.PORT || 8080
const app = express()

// 通常用于加载静态资源
app.use(express.static(__dirname + &#39;/public&#39;))

// 在你应用 JavaScript 文件中包含了一个 script 标签
// 的 index.html 中处理任何一个 route
app.get(&#39;*&#39;, function (request, response){
 response.sendFile(path.resolve(__dirname, &#39;public&#39;, &#39;index.html&#39;))
})

app.listen(port)
console.log("server started on port " + port)

When using Node as When serving, you need to use the wildcard * to listen to all requests and return the target html document (html referencing the js resource).

Nginx

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


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

Apache

If you use the Apache server, you need to create a .htaccess file in the project root directory. The file contains the following content:


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

The following are configurations for the server. Unfortunately, we have not introduced the relevant server yet. We just use the built-in service of webpack-dev-server, but we have found the problem. The problem is that the routing request cannot match the returned HTML document, so it is time to find a solution in the webpack-dev-server document.

webpack-dev-server

I have to complain about the official webpack-dev-server document. The blogger has read it several times. , I saw the problem clearly. There are two situations here:

  1. output.publicPath is not modified, that is, there is no declared value in the webpack configuration file, which is the default situation;

  2. Set output.publicPath to a custom value;

Click here to view the document

Default condition

By default, the output.publicPath value is not modified. You only need to set the historyApiFallback configuration of 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 problem 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 modified the output.publicPath value in your webpack configuration file , then you need to declare the request redirection and configure the historyApiFallback.index value.


// output.publicPath: &#39;/assets/&#39;
historyApiFallback: {
 index: &#39;/assets/&#39;
}

Proxy

I found that using the above method does not completely solve my problem. There will always be routing requests. The response was abnormal, so the blogger continued to look for 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.

代理提供通过函数返回值响应请求方式,针对不同请求进行不同处理,函数参数接收HTTP请求和响应体,以及代理配置对象,这个函数必须返回false或URL路径,以表明如何继续处理请求,返回URL时,源请求将被代理到该URL路径请求。


proxy: {
 &#39;/&#39;: {
  target: &#39;https://api.example.com&#39;,
  secure: false,
  bypass: function(req, res, proxyOptions) {
   if (req.headers.accept.indexOf(&#39;html&#39;) !== -1) {
    console.log(&#39;Skipping proxy for browser request.&#39;);
    return &#39;/index.html&#39;;
   }
  }
 }
}

如上配置,可以监听https://api.example.com域下的/开头的请求(等效于所有请求),然后判断请求头中accept字段是否包含html,若包含,则代理请求至/index.html,随后将返回index.html文档至浏览器。

解决问题

综合以上方案,因为在webpack配置中修改了output.publicPath为/assets/,所以博主采用webpack-dev-server Proxy代理方式解决了问题:


const PUBLICPATH = &#39;/assets/&#39;
...
proxy: {
 &#39;/&#39;: {
  bypass: function (req, res, proxyOptions) {
   console.log(&#39;Skipping proxy for browser request.&#39;)
   return `${PUBLICPATH}/index.html`
  }
 }
}

监听所有前端路由,然后直接返回${PUBLICPATH}/index.html,PUBLICPATH就是设置的output.publicPath值。

另外,博主总是习惯性的声明,虽然不设置该属性也能满足预期访问效果:


historyApiFallback: true

相关推荐:

使用Django实现自定义404,500页面的方法

IDEA导入web项目详解(解决访问的404)

thinkphp制作404跳转页的简单实现方法

The above is the detailed content of How to solve react-router browserHistory refresh page 404 problem. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools