Home > other >  React js website is thowing error on refresh?
React js website is thowing error on refresh?

Time:05-03

I'm reposting this with more information, this is driving me crazy so any help is appreciated. I've created a website with react (node.js) and deployed it.

I have 3 pages on my website and they all work fine (using react-router-dom for navigation) except for a really strange issue when I refresh 2 of the pages (all pages except home page) I get this error message:

Not Found The requested URL was not found on this server. Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

When I google this people say that a ".htaccess" file is needed with some extra lines but I'm a beginner to react js so I don't know what this means or how/where to create one. Can someone help me with this?

Thank you!!

App.js
import { Route, Routes } from 'react-router-dom';

function App() {
  return (
    <div className="App">
      <Routes>
        <Route path="/" element={<Home/>}/>
        <Route path="/about" element={<About/>}/>
        <Route path="/work" element={<Work/>}/>
      </Routes>
    </div>
  );
}

export default App;

CodePudding user response:

Okay so don't know if this will help anyone but this solved it:

  • log into cpanel

  • create a file under public html under file manager

  • name it .htaccess

  • paste this:

    RewriteEngine On RewriteBase / RewriteRule ^index.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L]

voila! (hopefully)

CodePudding user response:

TBH, this one is kind of a hack. Have you ever seen those URLs with # in them? They're using Hash History.

The idea is by appending a # to the end of the root of your URL, anything after that # won't be sent to the server. So if the URL was https://ui.dev/#/courses, the browser would make a GET request to https://ui.dev, get back all the JavaScript, React Router would then load, see /courses, and show the proper view for that route. React Router provides a HashRouter component you could use that will get you hash-based routing, but honestly, unless you REALLY need it, there are better options.

CodePudding user response:

Why are you not using Router tag to contain all the child elements? I have never seen Routes before. Try Router and Switch (Maybe you can wrap Routes with Router or use Switch tag instead of Routes)

Here's a good cheatsheet: https://www.freecodecamp.org/news/react-router-cheatsheet/

  • Related