最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - While refreshing the react js project it gives 404 error - Stack Overflow

programmeradmin3浏览0评论

I created a project based on React JS and also uploaded the file to the server but when I navigate to another link tab like https://localhost:3000/about and refresh the page it gives the 404 error. How I can solve this problem?

I created a project based on React JS and also uploaded the file to the server but when I navigate to another link tab like https://localhost:3000/about and refresh the page it gives the 404 error. How I can solve this problem?

Share Improve this question edited Jul 27, 2022 at 5:21 asked Jul 27, 2022 at 5:17 user18628737user18628737 3
  • localhost/about doesn't seem like a valid url. there is probably a port like localhost:3000/about – nullptr Commented Jul 27, 2022 at 5:19
  • I just give the path like /about – user18628737 Commented Jul 27, 2022 at 5:20
  • @nullptr notice the m as the last character, and "uploaded the file to the server". this is deployed to a production server – Samathingamajig Commented Jul 27, 2022 at 5:30
Add a ment  | 

3 Answers 3

Reset to default 3

I was getting 404 whenever i was refreshing the page. So what i did is...

If you have build your React JS App using

yarn build
OR 
npm run build

and is being hosted on an Apache Server. Then you can add htaccess on the root of the application

 <IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-l
  RewriteRule . /index.html [L]
</IfModule>

if you are using something other than apache please refer to this link, it might help

https://tecadmin/solving-react-404-error/

I hope this might help someone in the future.

This seems to be because you're doing client side routing with a library (the most popular one is react-router-dom). This works when you start on the root page, but since you've deployed on a static server if you were to reload on any other path than / you'd get a 404. To fix this, you have a couple options:

  • Use a HashRouter
  • Get a more plex server that returns index.html instead of a 404 on any GET requests that aren't fulfilled by a file
  • Upgrade to a fullstack React-based framework that handles routing, like NextJS, Gatsby, Remix, etc.

this error gets when you build react app and render the file as statice files
you need to create render route return react files like this:

//expressjs
    app.get("*",(req,res)=>{
    
    retrun YourReactProjectIndexFile()
    
    })
发布评论

评论列表(0)

  1. 暂无评论