eveo eveo - 6 months ago 186
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

/test
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 = (
<div>
<Route path="/" component={ AppContainer }>
<IndexRoute component={ RegistrationContainer }/>
<Route path="test" component={ StripeContainer }/>
</Route>
</div>
)

export default routes

Answer

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.

routes

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

// 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');

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