Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to let react router respond with 404 status code?

I'm using react router as root and all requests under "/" are directed to react router. And when react router found that the url is not matched with any of the defined components, it renders with NoMatch component. And here goes the problem, NoMatch is rendered and that's what I want, but the status code is still 200 instead of 404. And when my css or js files are placed with a wrong url react router does the same thing, it responds with 200! And then the page tells me that there's some problem with my resources content type!

So, how can I use react router to handle everything in the "/" and still get it to treat 404 errors right(to respond with 404 status code)?

code in react router

render((
  <Router history={browserHistory}>
    <Route path="/" component={App}>
      <IndexRoute component={Index}/>
      <Route path="archived" component={App}>
        <IndexRoute component={ArchivedPage}/>
        <Route path="project/:projectId" component={ArchivedDetailPage}/>
      </Route>
      <Route path="*" component={NoMatch}/>
    </Route>
  </Router>
), document.getElementById('app'));

the servre side

  router.use('/', function(req, res, next) {
    res.render('index-react', {
      title: 'some title'
    });
  });
like image 773
Liang Avatar asked Mar 17 '16 05:03

Liang


People also ask

How do I redirect a 404 page in React router?

Every Website needs a 404 page if the URL does not exist or the URL might have been changed. To set up a 404 page in the angular routing, we have to first create a component to display whenever a 404 error occurred.

How do I enable routing in React?

To enable routing in our React app, we first need to import BrowserRouter from react-router-dom . This should hold everything in our app where routing is needed. That means, if we need routing in our entire app, we must wrap our higher component with BrowserRouter .


4 Answers

With react-router 2.0.0 you can do:

<Route path="*" component={NoMatch} status={404}/>

EDIT:

What you would need to do, is to create a custom attribute on your route definition, like you can see above (status).

When you are about rendering you component on server side, check on this attribute and send a response with a the code of this attribute:

routes.js

import React from 'react';
import {IndexRoute, Route} from 'react-router';

import {
    App,
    Home,
    Post,
    NotFound,
} from 'containerComponents';

export default () => {
    return (
    <Route path="/" component={App}>

        <IndexRoute component={Home} />
        <Route path='post/' component={Post} />

        { /* Catch all route */ }
        <Route path="*" component={NotFound} status={404} />

    </Route>
  );
};

server.js:

import { match } from 'react-router';
import getRoutes from './routes';
....
app.use((req, res) => {
match({ history, routes: getRoutes(), location: req.originalUrl }, (error, 
        redirectLocation, renderProps) => {
        if (redirectLocation) {
          res.redirect(redirectLocation.pathname + redirectLocation.search);
        } else if (error) {
          console.error('ROUTER ERROR:', error);
          res.status(500);
        } else if (renderProps) {

            const is404 = renderProps.routes.find(r => r.status === 404) !== undefined;
        }
        if (is404) {
          res.status(404).send('Not found');
        } else {
            //Go on and render the freaking component...
        }
    });
});

Sorry about that... certainly my solution wasn't working by itself, and I missed the proper piece of code where you actually check on this attribute and render accordingly.

As you can see, I just send the 'Not found' text to the client, however, it would be best if you catch the component to render from renderProps (NoMatch in this case) and render it.

Cheers

like image 189
rmartrenado Avatar answered Oct 19 '22 20:10

rmartrenado


I did some digging, this is how we do things in the v4 release.

<Route
  render={({ staticContext }) => {
    if (staticContext) {
      staticContext.statusCode = 404
    }
    return <NotFound />
  }}
/>

The Route component is used to access the staticContext which has a statusCode prop that you can set if you use the StaticRouter component to render on the server.

Server code looks something like this (with some TypeScript typing)

const currentLocation: Location = {
  pathname: req.pathname,
  search: req.search,
  hash: '',
  state: undefined
}

const staticRouterContext: StaticContext & StaticRouterContext = {}

ReactDOMServer.renderToString(
  <StaticRouter location={currentLocation} context={staticRouterContext}>
  ...
  </StaticRouter>
)

if (staticRouterContext.statusCode) {
  res.status(staticRouterContext.statusCode)
}

Note: I think the typings are a bit wonky because the StaticRouterContext doesn't have the statusCode prop from the StaticContext interface. Probably a mistake in the typings. This works just fine though.

like image 44
John Leidegren Avatar answered Oct 19 '22 20:10

John Leidegren


Zen: What is the error code of a silent network?

I puzzled on this question as well. The odd case, you don't change the HTTP error code. We think we should, because a random URL was called, but why?

In a SPA (Single Page Application), there isn't network traffic but just switching of panes. The HTTP error code is in the headers for serving a new page, while all the content is in a named <div> that doesn't reload a new page. One would need to toss out page, transmit and render a new page to have the 404 return code, and then send the original page again when the user moves away.

And, its only the user. The 404 error code, or any other HTTP code, is really a hint to the browser or service. If the requester is a browser, the human is given a better indication than the browser could provide. If the requestor is a crawler, it probably scans for 404 in <h1>'s. If the requester is using your website as an API, why is that a good thing?

So the answer is that we set the HTTP status codes out of habit. Don't.

like image 38
Charles Merriam Avatar answered Oct 19 '22 21:10

Charles Merriam


To do this, you need to run the match on the server as well, to see if a route matches. Of course, if you're going to do this, you may well do full-fledged server-side rendering as well! Consult the server rendering guide.

like image 38
taion Avatar answered Oct 19 '22 21:10

taion