解决 create-react-app 打包后子页面刷新 404 问题
在使用 create-react-app 构建 React 项目时,我们经常会遇到一个问题:在打包后的项目中,刷新子页面会出现 404 错误。这是因为在 React 中,我们通常使用的是单页应用(SPA)模式,而在子页面刷新时,服务器没有相应的路由配置,因此会出现 404 错误。
那么如何解决这个问题呢?接下来,我们将为大家详细介绍两种解决方案。
方案一:使用 HashRouter
HashRouter 是 React Router 提供的一种路由模式,它通过 URL 中的 hash 值来实现路由切换,从而避免了子页面刷新时的 404 错误。下面是示例代码:
// www.javascriptcn.com code example
import React from 'react';
import { HashRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';
function App() {
return (
<Router>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
</Switch>
</Router>
);
}
export default App;在上面的代码中,我们使用 HashRouter 替换了原来的 BrowserRouter,并在 Route 中添加了 exact 属性,以确保主页能够正确匹配。此外,我们还需要修改打包后的 index.html 文件,将所有的 href 属性中的 / 替换为 #/,如下所示:
// www.javascriptcn.com code example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script src="%PUBLIC_URL%/static/js/bundle.js"></script>
<script src="%PUBLIC_URL%/static/js/0.chunk.js"></script>
<script src="%PUBLIC_URL%/static/js/main.chunk.js"></script>
<script>
if (window.location.href.indexOf('#/') === -1) {
window.location.href = window.location.href.replace(
window.location.origin,
window.location.origin + '#/'
);
}
</script>
</body>
</html>在上面的代码中,我们添加了一个判断,如果 URL 中没有 #/,则将其替换为 #/,从而确保 HashRouter 能够正确运行。
方案二:使用 Nginx 配置
除了使用 HashRouter,我们还可以通过 Nginx 配置来解决子页面刷新时的 404 错误。下面是示例配置文件:
// www.javascriptcn.com code example
server {
listen 80;
server_name yourdomain.com;
root /path/to/your/project/build;
location / {
try_files $uri /index.html;
}
}在上面的配置文件中,我们将服务器的根目录设置为打包后的 build 文件夹,并在 location 中添加了 try_files 指令,用于匹配静态资源和路由。如果找不到对应的资源,则将请求转发到 index.html 文件。
通过上述两种方案,我们可以轻松解决 create-react-app 打包后子页面刷新 404 问题,从而提高项目的稳定性和用户体验。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d50ab8a941bf713495a16f