我们将react-roucter-dom与http-server结合使用,当用户加载主页并单击导航链接时,新页面将完美加载,但当用户在该路径中刷新页面时,将返回404。这意味着HTML5 pushState没有使用http-server。
例子:
<Router>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/topics" component={Topics} />
</Router>如果用户转到/about页面并刷新它,则会发生404错误。
有办法解决这个问题吗?
发布于 2020-03-31 03:48:29
当您运行http-server时,请使用此方法:
http-server --proxy http://localhost:8080? ./build它将无法处理的任何错误请求重定向到您的react路由器配置所在的index.html。如果所有的请求都出现在这个页面上,那么react路由器就会负责内部的路由。
顺便说一句,我在package.json脚本中构建了一个小脚本,调用所有这些脚本并像这样为构建文件夹提供服务:
scripts: {
...
"serveprod": "npm run build && http-server --proxy http://localhost:8080? ./build"
...
}就跑吧:
npm run serveprod发布于 2019-02-04 08:21:29
您应该使用其他支持HTML5历史API的包,比如瑟夫尔,而不是http-server。
发布于 2021-11-06 03:37:05
我在我的反应+ Webpack项目中也有同样的问题。我在创建-反应性-应用程序文档上找到了解决方案。
你必须:
npm i --save express (链接)server.js)index.html
// libs
const express = require("express");
const path = require("path");
// create server
const app = express();
const PORT = 3000;
const BUILD_FOLDER = "public";
app.use(express.static(path.join(__dirname, BUILD_FOLDER)));
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, BUILD_FOLDER, "index.html"));
});
app.listen(PORT);
node server.js (活动控制台)或node server.js 1>server.log 2>server-error.log & (后台进程,您稍后可以在ps uax | grep node中找到)启动服务器我知道这篇文章很旧,但也许有人会发现它很有用。
https://stackoverflow.com/questions/54511950
复制相似问题