skip to Main Content

I’m building an application with Reactjs and Nodejs and I’ve built all my routes using React-Router-Dom

`

<BrowserRouter>
  <Routes>

    <Route path='/' element={<Home />} />
    <Route path='/receitas' element={<Receitas />} />
    <Route path='/receita/:id' element={<ReceitaPage />} />
    <Route path='/login' element={<Login />} />
    <Route path='/crud' element={<Crud />} />
    <Route path='/ebook/:id' element={<EbookPage />} />

  </Routes>

</BrowserRouter>`

When I move between my pages using the front-end buttons, the site works correctly because either I use the functionality <Link to={}> </Link/> or I use UseNavigate();.

But I’m having problems when I access the site directly with the link, I’ll show you a picture of when I use the button on the page: Image Here

When I access the same link writing in the browser itself, this message appears to me: Second Image Here

The browser recognizes it as another type of route.

I’m using Nodejs for my Back-End and I really don’t know what to do about it. Can anyone help me, why I don’t know if I can fix it using Reactjs or Nodejs?

2

Answers


  1. The difference is that when you write directly in the browser it is retrieving the route from the node server. On the other hand, when you navigate using the react router link it’s doing client side routing and never hits the server.

    If you plan on doing all of the routing with react router, you can add a catch-all in the node server for all routes that will always return the single page HTML index.

    Assuming you are using express, you can do something similar to this

    app.get('*', (req, res) => {
      res.sendFile('path/to/your/index.html');
    });
    
    Login or Signup to reply.
  2. Are you rendering your React build using NodeJS? If so, you’ll have to instruct your backend to always render index.html.

    You’ll have to do something like this in your server:

    // Handle React routing, return all requests to React
    app.get('*', function(req, res) { 
        res.sendFile(path.join(__dirname, 'client/build', 'index.html')); 
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search