Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react router 4 and express : cannot GET

I'm trying to use react router 4, with an Express server.

If I set the path to "/", it works. But if I set the path "/test", and visit test, I get "Cannot GET /test". Is it because React Router 4 is incompatible with Express ?

app-client.js:

import { BrowserRouter, Route, Switch } from 'react-router-dom';
import Board from './components/Board';

ReactDOM.render(
    <BrowserRouter>
        <div>
            <Route path="/test" component={Board} />
        </div>
    </BrowserRouter>
    , document.getElementById('react-container'));

Board.js:

var React = require('react');
var createReactClass = require('create-react-class');

var Board = createReactClass({
    render(){
        return (<h1>Board</h1>)
    }    
});

export default Board;
like image 317
trogne Avatar asked Dec 11 '22 07:12

trogne


2 Answers

To make sure all your routes are handled by React after defining all you express routes we will make sure any route that is not handled in express app will be redirected to the index.html in the react app to be handeled like so:

// All expressjs routes
// then
app.get('*', (req, res) => {                       
  res.sendFile(path.resolve(__dirname, 'the path to your react project', 'index.html'));                               
});
like image 116
Amr Aly Avatar answered Dec 28 '22 06:12

Amr Aly


I had the same issue as OP and followed Amr Aly's directions AS WELL as checking out a couple blog posts and github issues, like the following: https://tylermcginnis.com/react-router-cannot-get-url-refresh/

However, after following their directions, this error would get thrown:

“Uncaught SyntaxError: Unexpected token <”

You then go on a wild goose chase, as seen here in this SO post.

To resolve OP's issue AND not deal with the uncaught syntax error, try the following:

if (process.env.NODE_ENV === 'production') {
  const publicPath = path.join(__dirname, '../public');
  app.use(express.static(publicPath));
  app.use('*', express.static(publicPath));
}
like image 26
Andrew Patterson Avatar answered Dec 28 '22 06:12

Andrew Patterson