SHZhao74
SHZhao74

Reputation: 93

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...

Upvotes: 3

Views: 2432

Answers (3)

SHZhao74
SHZhao74

Reputation: 93

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...

Upvotes: 2

kkshyu
kkshyu

Reputation: 1

First, I thought you misunderstood the server part. In your case, you use serve as your server. This is a static server provided by [serve]. If you want to use your own server.js, you should run node server.js or node server.

I also did the same things with you and have no this issue. The followings are what I did:

  1. create-react-app my-app
  2. npm run build
  3. sudo serve -s build -p 80 (sudo for port under 1024)

And I got the results:

/user/321

I guessed you might forget to build the script. You can try the followings:

  1. remove build/ folder
  2. run npm run build again

Advise: If you want to focus on front-end, you can just use [serve]. It will be easy for you to focus on what you need.

Upvotes: 0

max-lt
max-lt

Reputation: 1421

If your route /user/** is defined after app.get('/*', ... it might not match because /* gets all the requests and returns you index.html. Try without the * or declare the other routes before.

Upvotes: 0

Related Questions