Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React router doesn't work on express server

I am new to react, and I am trying to build a chat-app with it. I used react-router to load different components according to the url. In my react project foler (client/src/index.js), the code is as follows:

import {BrowserRouter as Router, Route} from 'react-router-dom';    
...
ReactDOM.render(
  <Router>
    <div>
      <Route exact path='/' component={App} />
      <Route path='/customer' component={CustomerPage} />
      <Route path='/support/:support_id' component={SupportPage} />
    </div>
  </Router>,
  document.getElementById('root')
);
...

It works find when I start it in the react folder with "npm start". But when I run "npm run build" and serve the static files with express server, it can only serve the App page in the '/' path, while for '/customer' and '/support/:support_id" path, it loads nothing.

In the express server folder, I load the static files in the following way:

server/app.js:

...
var indexRouter = require('./routes/index');
app.use('/static', express.static(path.join(__dirname, '../client/build//static')));
app.use('/', indexRouter);
...

server/routes/index.js:

...
router.get('/', function(req, res) {
  res.sendFile('index.html', {root: path.join(__dirname, '../../client/build/')});
});
...

Any help will be appreciated!

like image 212
Hiber Avatar asked Jul 08 '18 00:07

Hiber


2 Answers

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/')});
});
like image 178
Tholle Avatar answered Sep 26 '22 08:09

Tholle


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 app
app.use(express.static(path.join(__dirname, 'client/build')));

// Handles any requests that don't match the ones above
app.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);
like image 45
Nicolai Pefaur Zschoche Avatar answered Sep 26 '22 08:09

Nicolai Pefaur Zschoche