Express 如何为webpack构建的production react bundle.js服务?

Express 如何为webpack构建的production react bundle.js服务?,express,reactjs,webpack,react-router,production,Express,Reactjs,Webpack,React Router,Production,我的应用程序在网页包开发服务器中运行良好。现在,我想把它部署到我的生产服务器上。所以我构建了bundle.js。我尝试在express server上提供该文件,但除了根/之外,我无法访问其他URL 例如,以下是我的反应路线: var Routes = () => ( <Router history={browserHistory}> <Route path="/" component={Landing}>

我的应用程序在网页包开发服务器中运行良好。现在,我想把它部署到我的生产服务器上。所以我构建了bundle.js。我尝试在express server上提供该文件,但除了根
/
之外,我无法访问其他URL

例如,以下是我的反应路线:

var Routes = () => (
    <Router history={browserHistory}>
        <Route path="/" component={Landing}>
        </Route>
        <Route path="/app" component={App}>
        </Route>
    </Router>
)
登录页http://localhost:3000/ 作品但是应用程序http://localhost:3000/app 不。相反,我遇到了一个错误
无法获取/app

您需要在express服务器上声明一个“捕获所有”路由,该路由捕获所有页面请求并将它们定向到客户端。首先,确保在服务器上包含
路径
模块:

var path = require('path');
然后,把这个放在应用程序前面。听一下:

app.get('*', function(req, res) {
  res.sendFile(path.resolve(__dirname, 'public/index.html'));
});

这假设您正在通过脚本标记将
bundle.js
插入
index.html

谢谢,效果非常好!在解决方案中发现一个小的输入错误:应该是res.sendFile(path.resolve(uu dirname
'public/index.html');伟大的同样感谢您注意到,我已经编辑了答案。这与我的设置相同。您只需将./dist/bundle.js复制到./public即可(确保bundle.js的路径与index.html中定义的相对路径相匹配——在您的情况下应该是./public/dist/bundle.js)。您需要记住在每个版本中都要这样做。我认为您可以使用脚本、webpack插件或gulp任务自动执行此操作。遵循此方法,当Get请求完成时,它将返回html文件作为reponse@tscizzle是的,我通过改变一些行的顺序得到了修复,只是app.get('*',function(req,res){res.sendFile(path.resolve(u dirname,'public/index.html');});最后,在其他路由和服务器之前。侦听(端口);
app.get('*', function(req, res) {
  res.sendFile(path.resolve(__dirname, 'public/index.html'));
});