eveo eveo - 1 year ago 278
Node.js Question

Express overwrites react-router client side routes

I don't want to use server side rendering because it is an absolute pain to get working and I've gotten everything working without it.

However if I make a new url like

and visit localhost:3000/test I get
Cannot get /test

This is how my index page is being served up

app.get("/", function(req, res) {
res.sendFile(__dirname + '/client/index.html')

routes file

const routes = (
<Route path="/" component={ AppContainer }>
<IndexRoute component={ RegistrationContainer }/>
<Route path="test" component={ StripeContainer }/>

export default routes

Answer Source

I'm working on this right now and I think you'll need to declare the /test path before the React route.

How I'm going to implement it in my app is declare some routes in Express for user login and then have a catchall at the end to send anything else to React.

Something like

app.get('/login', function(...));
app.get('/logout', function(...));
app.get('*', <TO-REACT>);

I'm not sure if this is the right way to go about dealing with this issue but it should work.

Let me know how it works for you or if you foresee any issues using this.

Update: I can confirm that this is working for me now. Here are abbreviated versions of my express routes file and base React file.


// redirects any requests to root of domain to React (a polling app)
app.get('/', function(req, res) {

// authentication routes
app.get('/login' function(....));
app.get('/logout' function(....));
app.get('/login/callback' function(....));
app.get('/login/authorise' function(....));

// React catch all route
app.get('*', function(....{sendfile....});

base react file

import React from 'react';
import ReactDOM from 'react-dom';
import {Router, Route, Redirect, browserHistory} from 'react-router';

const PollListScreen = require('./PollListScreen.js');
const PollAdd = require('./PollAdd.js');

  <Router history={browserHistory}>
    <Route path='/polls' component={PollListScreen} />
    <Route path='/polls/new' component={PollAdd} />
  ), document.getElementById('app')