My app works fine in webpack development server. Now, I want to deploy it to my production server. So I built bundle.js. I tried serving the file on express server, but I can't access urls other than the root /
.
For example, here is my react routes:
var Routes = () => (
<Router history={browserHistory}>
<Route path="/" component={Landing}>
</Route>
<Route path="/app" component={App}>
</Route>
</Router>
)
and express app (I put bundle.js
and index.html
in ./public
):
app.use(express.static('./public'));
app.listen(port, function () {
console.log('Server running on port ' + port);
});
Landing page http://localhost:3000/ works. But the app http://localhost:3000/app doesn't. Instead, I got an error Cannot GET /app
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With