React-router: How to handle direct routes using Express.js?

Created on 4 Apr 2015  路  2Comments  路  Source: ReactTraining/react-router

Hello,

I've currently got my application working with routing, using Express.js:

var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
var app = express();

app.set('port', (process.env.PORT || 3000));

app.use('/', express.static(path.join(__dirname, 'dist')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.listen(app.get('port'), function() {
  console.log('Server started on port ' + app.get('port'));
});

This works, and going to http://127.0.0.1:3000 loads the react application, with working routes (HTML5/No hashes).

However, when I try to directly go to a route, say http://127.0.0.1:3000/profile, I get the Express message "Cannot GET /profile".

How do I handle this, so I'm able to visit the route and have it load everything as expected?

Cheers

Most helpful comment

Ah this seemed to make it work:

app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', function(req, res) {
    res.sendfile('./dist/index.html');
});

All 2 comments

You need to add an astericks to tell express to pass all routes to the same handler.

app.all('/*', handler);

Your handler should call res.render to load the initial index page of your app. This way any endpoint will always send your app.

This isn't really an issue with react-router and it's best to ask such questions here https://gitter.im/strongloop/express

Ah this seemed to make it work:

app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', function(req, res) {
    res.sendfile('./dist/index.html');
});
Was this page helpful?
0 / 5 - 0 ratings

Related issues

misterwilliam picture misterwilliam  路  3Comments

maier-stefan picture maier-stefan  路  3Comments

yormi picture yormi  路  3Comments

stnwk picture stnwk  路  3Comments

alexyaseen picture alexyaseen  路  3Comments