【发布时间】:2019-12-04 00:43:55
【问题描述】:
我有一个前端 React 应用和一个后端 Express 应用在两个不同的 Heroku dyno 上运行。据我所知,前端服务器不知道我的 Express 应用程序,除非我专门向该 API 发送查询。相反,我的 React 应用程序以某种方式基于默认设置提供服务,可能由 create-react-app 提供。
但是,我目前正在使用我的 React Router 路由遇到this issue,他们提供的解决方案是将此代码添加到服务器:
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "index.html"));
});
当然,我的 Express 应用程序中已经存在该代码,但我们已经确定这不是为我的 React 应用程序提供服务的代码。那么我在哪里添加相同(或相似)的代码以确保我捕获所有可能的路线并将它们发送到“index.html”?
更新:
从我完成的附加阅读来看,看起来 Webpack 路由回 index.html 的方式是在 webpack.config.js 中将 historyApiFallback 设置为 true。但是,我不打算退出 CRA,因为我认为这将导致比它解决的更多的长期问题。在我的 node_modules/react-scripts/config 文件夹中,在 webpackDevServer.config.js 文件中,这已经存在:
historyApiFallback: {
// Paths with dots should still use the history fallback.
// See https://github.com/facebook/create-react-app/issues/387.
disableDotRule: true,
}
除非我误读了this doc,否则这似乎相当于说historyApiFallback = true。那么这不应该已经起作用了吗?
我发现的另一件事是,大多数人只在开发过程中遇到这种行为的问题,因为热重载功能只在开发过程中开启。但是,我的理解是当我部署到 Heroku 时,它会自动构建我的应用程序的生产版本。但是从“/signup”到“/”的自动重定向也发生在那里。如果 historyApiFallback 没有解决问题,那会是什么?
路由文件:
<Switch>
<Route exact path="/" component={App} />
<Route path="/home" component={LandingPage} />
<Route exact path="/signup" render={props => (
<AuthPage authType="signup" {...props} />
)} />
<Route path="/login" render={props => (
<AuthPage authType="login" {...props} />
)} />
<Route path="/about" component={AboutPage} />
</Switch>
【问题讨论】:
-
你在使用 webpack 来打包 React 吗?如果是这样,那就是它的配置位置,
webpack.config.js中的output。 -
我正在使用默认使用 Webpack 的 create-react-app。我不需要弹出来配置它,对吧?我注意到我在 node_modules 树的不同位置有许多 webpack.config.js 文件。似乎最有可能的是 node_modules > webpack-dev-server > client > webpack.config.js 但这没有任何输出选项
-
我不建议更改 node_mofiles 中的任何内容。
-
您可能想查看 CRA 文档中推荐的这篇文章:auth0.com/blog/how-to-configure-create-react-app
-
当我想象 99% 的 React/React 路由器用户都希望能够键入 www. mydomain.com/signup 并且不让它重定向到 www.mydomain.com/
标签: reactjs react-router create-react-app