1

I'm trying to serve a react app (that use router) using express. The react app supposedly is accessible through /dashboard.

Everything is working well on the /dashboard route that supposed to show the login page. But if I try to access different routes, example /dashboard/foo It shows nothing. It turns out when the HTML page request the .js file, the server return with the index.html file instead of the .js file.

I'm using this code in the index.js file:

app.use(
  ['/dashboard', '/dashboard/*'], 
  express.static(path.join(__dirname, 'dashboard')),
);

have also tried this code:

app.use(
  '/dashboard',
  express.static(path.join(__dirname, 'dashboard')),
);
app.get(
  '/dashboard/*',
  (req, res) => {
    res.sendFile(__dirname + "/dashboard/index.html"));
  }
);
Steven
  • 539
  • 4
  • 11
  • You could just redirect all routes to index.html from express side and let react router do its magic and taking care of all routes including `/dashboard` and `/dashboard/foo` – tarzen chugh Oct 06 '19 at 07:23
  • @tarzenchugh the thing that it's actually just `/` and `/foo` in react-router. And the express also used to serve another route such as `/api/bar` – Steven Oct 06 '19 at 07:30

1 Answers1

0

He, routers define order is make sense, Here is go example Order of router precedence in express.js and documentation https://expressjs.com/en/guide/routing.html

when you try to access /dashboard/something, because of /dashboard 1st in order, you ever access /dashboard and not /dashboard/somethink, all about order here

  • This doesn't work and it seems like even if I don't change the order, `/dashboard/something` should always go to `/dashboard/something` even if it meets `/dashboard` first – Steven Oct 06 '19 at 09:11