user18628737
user18628737

Reputation:

While refreshing the react js project it gives 404 error

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?

enter image description here

Upvotes: 2

Views: 10519

Answers (3)

Ahmad Gulzar
Ahmad Gulzar

Reputation: 127

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.net/solving-react-404-error/

I hope this might help someone in the future.

Upvotes: 3

Jawad Fadel
Jawad Fadel

Reputation: 820

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()
    
    })

Upvotes: 0

Samathingamajig
Samathingamajig

Reputation: 13245

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

Upvotes: 0

Related Questions