【发布时间】:2019-10-01 13:36:51
【问题描述】:
我的 Heroku 应用正在使用 React 和 React Router。我使用 Switch 来浏览不同的组件,因此 URL 也会发生变化(例如 /room/4141)。但是,如果我重新加载页面,它不会像 React 应用程序那样运行,而是会搜索提到的 .html 文件。
我使用了这个 Buildpack:https://github.com/mars/create-react-app-buildpack.git,但它似乎对将页面重写为 index.html 没有任何作用。
有没有办法阻止这种行为并将所有 URL 重写为 index.html?
**编辑:
我对 express 不够熟悉,但这里是 index.html 的服务方式。
const express = require("../../node_modules/express");
const app = express();
const server = require("http").Server(app);
const io = module.exports.io = require('../../node_modules/socket.io/lib')(server)
const path = require("path")
app.use(express.static(path.join(__dirname, '../../build')));
if(process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, '../../build')));
console.log("DEBUG HERE", __dirname, path.join(__dirname+'../../build'));
//
app.get('/*', (req, res) => {
res.sendFile(path.join(__dirname+'../../build/index.html'));
})
}
//build mode
app.get('/*', (req, res) => {
res.sendFile(path.join(__dirname+'../../public/index.html'));
})
【问题讨论】:
-
你可以使用带有哈希的客户端路由吗,例如
https://yoursite.com/#room/4141?这应该是开箱即用的。 -
似乎使用哈希也没有什么不同。我的页面根本没有加载。还是我做错了?
<Route path="/#room/:roomCode" component={Lobby} />*EDIT:重新加载页面也会返回Not Found
标签: reactjs heroku react-router