Search code examples
node.jsreactjsexpressreact-routerserve

Cannot get correct static files after refreshing except index page


When I refresh page on index route (/) and login page (/login), it works fine.

However, my website gets error as I refresh on other routes, for example /user/123456.

Because no matter what the request is, the browser always gets HTML file.
Thus, both of the content in main.css and main.js are HTML, and the browser error.

enter image description here

I have already read the README of create-react-app.
Whether I use serve package ($serve -s build -p 80) or express, it will produce the strange bug.

Following is my server code:

//server.js
const express = require('express');
const path = require('path');
app.use(express.static(path.join(__dirname, 'build')));
app.get('/*', (req, res) => {
  res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
const PORT = process.env.PORT || 80;
app.listen(PORT, () => {
  console.log(`Production Express server running at localhost:${PORT}`);
});

Edit: I have figured out where caused the problem.
I created a new project, and compared it to mine. The path of static files in the new project is absolute, but in my project is relative.
As a result, I delete "homepage": "." in the package.json.

//package.json
{ ....
  dependencies:{....},
  ....,
- "homepage": "."
}

Everything works as expected now. How am I careless...


Solution

  • I have figured out where caused the problem. I created a new project, and compared it to mine. The path of static files in the new project is absolute, but in my project is relative. As a result, I delete "homepage": "." in the package.json.

    //package.json
    { ....
     dependencies:{....},
     ....,
    - "homepage": "."
    }
    

    Everything works as expected now. How am I careless...