0

I have a react front-end with an express back end. The express just serves the static build files from the react side in production. I was having a problem with React routing working in production, as many have had, so I fixed it as so:

server.js:

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

app.get('/api/customers', (req, res) => {
  const customers = [
    {id: 2, firstName: 'Test', lastName: 'Case'},
    {id: 3, firstName: 'Foo', lastName: 'Bar'},
  ];

  res.json(customers);
});

The '/*' solve the routing problem in production, but now the fetch for the '/api/customers' does not work anymore.

customer.js:

  componentDidMount() {
    fetch('/api/customers')
      .then(res => res.json())
      .then(customers => this.setState({customers}, () => console.log('Customers fetched...', customers)))
      .catch(() => console.log('Error'));
  }

This fetch request logs 'Error' when ran. It seems as though the url for the api is changing somehow as a result of the '/*' change in server.js, but I am not sure how I should change the fetch argument to make it work. The fetch was working using just the '/':

server.js:

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

However, this obviously stops react routing from working in production. What do I need to change my fetch argument to in order to make this work?

1
  • what has this with react-router I dont get it? Commented Mar 18, 2018 at 16:19

2 Answers 2

1

Change the order of the routes in server.js:

app.get('/api/customers', () => {});
app.get('/*', () => {});

The routes in express are first come first served, and as "/api/customers" matches "/*", it will return your index.html if your list them the other way around.

Sign up to request clarification or add additional context in comments.

Comments

0

thank you so much for this solutiion @David Filipidisz !! The order DOES affect the routes. this is my working code

server.js

...ipmorts here ...

app.use('/users', require('./users/users.controller'));
app.use('/machineLearning', require('./machineLearning/machineLearning.controller'));
app.use('/public', require('./public/public.controller'));

//for Prod
app.use(express.static(path.join(__dirname,'../L10-ui/dist')));
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, '../L10-ui/dist', 'index.html'));
});```

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.