jSamsa
jSamsa

Reputation: 43

I'm learning to use React Router but I can't get to understand this behavior

I have an Express server which serves the build of Create-React-App. When the server is listening I navigate to http://localhost:8000/ and get my page as intended, I click the links and it navigates to them correctly e. g http://localhost:8000/someroute shows the UI as expected but if I reload the page (or navigate to it directly from the nav bar ) it shows plain JSON instead of the UI.

Here is a repo to show that behavior https://github.com/Prjoel/React-Router-Test.git

What I don't get is why it doesn't happen (everything works fine) when I request from the development server offered by npm start script.

Upvotes: 0

Views: 71

Answers (1)

Abir Taheer
Abir Taheer

Reputation: 2783

The reason for this has to do with the two different routers in play. I think the route you're talking about is /random. When you click on the link from your react app, the routing is handled by the front-end library react-router-dom. The page isn't actually getting refreshed, moreso the url in your browser gets changed using javascript and react-router renders a different component.

When you refresh the page manually, you're asking your browser to ask the server for "/random"

app.get('/random', (req, res, next) => {
  console.log('get request for random');
  const obj = { randomNumber: 'random ' + (Math.floor(Math.random() * 10)) }
  res.status(200).json(obj);
})

The server returns a json for the /random route and that's why you see a json. My suggestion is to prefix your server side API Routes with /api.

Upvotes: 1

Related Questions