Reputation: 93
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.
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
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
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:
create-react-app my-app
npm run build
sudo serve -s build -p 80
(sudo
for port under 1024)And I got the results:
I guessed you might forget to build the script. You can try the followings:
build/
foldernpm run build
againAdvise: 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
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