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;
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'));
});
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With