I have an app with simple routes. It works fine when I use webpack development server. Now, I want to deploy it to my production server. So I built bundle.js. However, I am not sure what's the correct way to serve the file on the server.
Most blog posts stop at building bundle.js or deploy it to heroku or nodejutsu. What should I do if I want to serve it on my own server?
I tried serving the file on express server, but I'm getting this error in the browser (this same route works fine with webpack-dev-server).
http://localhost:3000/app
Cannot GET /app
I have simple route like this. Landing page at / works fine, but I can't access /app route
var Routes = () => (
<Router history={browserHistory}>
<Route path="/" component={Landing}>
</Route>
<Route path="/app" component={App}>
</Route>
</Router>
)
Here is my server.js. I put bundle.js, index.html in ./public
app.use(express.static('./public'));
app.listen(port, function () {
console.log('Server running on port ' + port);
});
You need to declare a "catch all" route on your express server that captures all page requests and directs them to the client. First, make sure you're including the path
module on your server:
var path = require('path');
Then, put this before app.listen
:
app.get('*', function(req, res) {
res.sendFile(path.resolve(__dirname, 'public/index.html'));
});
This assumes you're inserting bundle.js
into index.html
via a script tag.
来源:https://stackoverflow.com/questions/35928766/whats-the-correct-way-to-serve-production-react-bundle-js-built-by-webpack