React router doesn't work on express server React router doesn't work on express server reactjs reactjs

React router doesn't work on express server


React Router does all the routing in the browser, so you need to make sure that you send the index.html file to your users for every route.

This should be all you need:

app.use('/static', express.static(path.join(__dirname, '../client/build//static')));app.get('*', function(req, res) {  res.sendFile('index.html', {root: path.join(__dirname, '../../client/build/')});});


You must serve the static files and handle any request in your index.js:

const express = require('express');const path = require('path');const app = express();// Serve the static files from the React appapp.use(express.static(path.join(__dirname, 'client/build')));// Handles any requests that don't match the ones aboveapp.get('*', (req,res) =>{    res.sendFile(path.join(__dirname+'/client/build/index.html'));});const port = process.env.PORT || 5000;app.listen(port);console.log('App is listening on port ' + port);


* worked instead of using / in app.get() otherwise it'll always show cannot get. Thanks @basse