404 problem occurs when refreshing the page in react-router
This article mainly introduces the solution to the 404 problem of react-router browserHistory refreshing the page. It is of great practical value. Friends in need can refer to it.
When using React to develop new projects, when encountering the refresh page, directly When accessing the secondary or tertiary route, the access fails and a 404 or resource loading exception occurs. This article analyzes this problem and summarizes the solution.
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, but when the project In the following two situations, nested routing and asynchronous loading of routes are often required:
We use a routing library such as react-router to build single-page application routing;
Use the html-webpack-plugin plug-in to dynamically inject the <script> tag of loaded js into the html document; </script>
At this time, accessing localhost:9090 is normal Loading pages and js and other files, 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:
-
Page loading failed and Cannot Get (404) was returned;
The service responded, but the html file output by webpack processing was not returned, resulting in the inability to load js resources. The second case is as follows: Picture:

So how do we deal with the problem of normal access and routing of 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:
react-router road front end is configured by;
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 I first checked the relevant configuration information of the react-router routing library and found that it was mentioned in the document When using browserHistory, a real URL will be created, and there will be no problem in handling the initial/request. However, after the jump route, when refreshing the page or directly accessing the URL, you will find that it cannot respond correctly. For more information, please check the reference document, which is also provided in the document. Several server configuration solutions have been proposed:
Node
const express = require('express')
const path = require('path')
const port = process.env.PORT || 8080
const app = express()
// 通常用于加载静态资源
app.use(express.static(__dirname + '/public'))
// 在你应用 JavaScript 文件中包含了一个 script 标签
// 的 index.html 中处理任何一个 route
app.get('*', function (request, response){
response.sendFile(path.resolve(__dirname, 'public', '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 to all requests and return the target html document (html that references 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 yet introduced the relevant server. We just used the built-in service of webpack-dev-server, but we have found the problem, that is, the routing request cannot match the returned HTML document, so it is time to find the solution in the webpack-dev-server document.
webpack-dev-server
I have to complain about the official webpack-dev-server document. The blogger read it several times before he saw the problem clearly. There are two situations here:
output.publicPath is not modified, that is, there is no declared value in the webpack configuration file, which is the default situation;
Set output.publicPath to a custom value;
Click here to view the document
Default condition
Default condition , without modifying the output.publicPath value, 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 the 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 modify the output.publicPath value in the webpack configuration file, then you need to declare the request redirection and configure the historyApiFallback.index value.
// output.publicPath: '/assets/'
historyApiFallback: {
index: '/assets/'
}Proxy
I found that using the above method could not completely solve my problem. There would always be routing request response exceptions, so the blogger continued to look for better solutions. 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: {
'/': {
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';
}
}
}
}如上配置,可以监听https://api.example.com域下的/开头的请求(等效于所有请求),然后判断请求头中accept字段是否包含html,若包含,则代理请求至/index.html,随后将返回index.html文档至浏览器。
解决问题
综合以上方案,因为在webpack配置中修改了output.publicPath为/assets/,所以博主采用webpack-dev-server Proxy代理方式解决了问题:
const PUBLICPATH = '/assets/'
...
proxy: {
'/': {
bypass: function (req, res, proxyOptions) {
console.log('Skipping proxy for browser request.')
return `${PUBLICPATH}/index.html`
}
}
}监听所有前端路由,然后直接返回${PUBLICPATH}/index.html,PUBLICPATH就是设置的output.publicPath值。
另外,博主总是习惯性的声明,虽然不设置该属性也能满足预期访问效果:
historyApiFallback: true
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
The above is the detailed content of 404 problem occurs when refreshing the page in react-router. For more information, please follow other related articles on the PHP Chinese website!
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython 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 ResourcesApr 15, 2025 am 12:16 AMPython 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.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AMThis article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base
JavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AMJavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft






