Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serve production react bundle.js built by webpack?

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.

like image 274
Komsit Prakobphol Avatar asked Mar 10 '16 22:03

Komsit Prakobphol


1 Answers

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.

like image 61
Rick Runyon Avatar answered Oct 20 '22 09:10

Rick Runyon