0

I have build a project started with create-react-app. I'm trying it to serve it with express. It works, but when I try to go to other routes, these routes are not working and my React app page is the only one thing that showing up. Could you explain me why please ? Here is my code.

const express = require('express');
const path = require('path');

const app = express();
const router = express.Router();

app.use(express.static(path.join(__dirname, 'build')));
app.use('/', router);

router.get('/api', (req, res) => {
    res.send("API endpoints! ;)")
});

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

app.listen(8080, () => {
    console.log('Listening on 8080');
})

I have tried the solution there `express.static()` keeps routing my files from the route but it doesn't work.

Tholle
  • 108,070
  • 19
  • 198
  • 189
vidu.sh
  • 537
  • 1
  • 3
  • 21
  • What happens if you remove the router `app.use('/', router);`, and write `router.get('*'` instead of `router.get('/*'`? – Tholle Jul 13 '18 at 20:47
  • Still the same. However, I have tried my code in private mode and it works. When I do what you have asked me for, /api gives me a 404 Is there something related to things stored by React to allow the app to work without being connected ? – vidu.sh Jul 13 '18 at 20:53
  • Try `router.get('/api/*'` instead, and make sure you have the cache disabled when your developer tools are open so you get the new result. – Tholle Jul 13 '18 at 20:55
  • 1
    It doesn't work neither (thanks, I have learned how to disable cache thanks to you!) – vidu.sh Jul 13 '18 at 21:04

1 Answers1

0

I think i know whats wrong... Make sure you restart your backend when you make a code change or use nodemon when developing.

Your code looks fine.

lrossy
  • 533
  • 3
  • 10
  • 1
    I thought you were making fun of me.. So I have closed express, refreshed my browser to check if the web server was really off, then I started the server again and it worked !! It also works fine with nodemon Thanks! Do you know what that's doing that? – vidu.sh Jul 13 '18 at 21:21
  • When you run nodejs it stays in memory until its restarted. Its not checking for changes. If you have a PHP background this usually is confusing since PHP gets executed on each request so any changes you make are there on the next request. – lrossy Jul 13 '18 at 21:28
  • Also no really wasn't making fun of you. I tried to rephrase it to be less negative but thats not exactly my strong suit. I had a feeling that was the problem because I tought beginners for a while and this is a common issue. – lrossy Jul 13 '18 at 21:30