我的应用程序在 webpack 开发服务器中运行良好。现在,我想将其部署到我的生产服务器。所以我构建了bundle.js。我尝试在 Express 服务器上提供文件,但无法访问除根 /
之外的 URL。
例如,这是我的 react 路线:
var Routes = () => (
<Router history={browserHistory}>
<Route path="/" component={Landing}>
</Route>
<Route path="/app" component={App}>
</Route>
</Router>
)
和express应用程序(我将bundle.js
和index.html
放在./public
中):
app.use(express.static('./public'));
app.listen(port, function () {
console.log('Server running on port ' + port);
});
登陆页面 http://localhost:3000/有效。但应用程序 http://localhost:3000/app 却没有。相反,我收到错误Cannot GET/app
。
最佳答案
您需要在 Express 服务器上声明一个“捕获所有”路由,以捕获所有页面请求并将它们定向到客户端。首先,确保您的服务器上包含 path
模块:
var path = require('path');
然后,将其放在 app.listen
之前:
app.get('*', function(req, res) {
res.sendFile(path.resolve(__dirname, 'public/index.html'));
});
这假设您通过脚本标记将 bundle.js
插入到 index.html
中。
关于express - 如何为Webpack构建的生产React Bundle.js提供服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35928766/