Send both 404 status and redirect to 404 component in react-router

泪湿孤枕 提交于 2019-12-06 04:24:05

问题


I have a react-router 3.0.0 setup with a NotFound component I'm showing as a fallback:

<Route component={NotFound} path="*"/>

However this returns a redirect and the google crawler is complaining about soft 404s. Can I both redirect to my NotFound component and send a 404, similar to what Github does for instance? I've tried the following suggestion from here: How to let react router respond with 404 status code?

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

But that just gives me a 404 without displaying the component.

How can the above be accomplished?


回答1:


Just to close the loop on this - I didn't want to go the server-side rendering route, so I implemented the following in my global error handler middleware:

     if (err.name === 'UnauthorizedError') {
        res.status(401).send(prepareErrorResponse(isXhr, 'Acess Denied'));
      } else if (err.status === 404) {
       res.status(404).send(prepareErrorResponse(isXhr, 'Not Found'));
       if (req.accepts('html')) {
         // Respond with html page.
         fs.readFile(__dirname + '/../404.html'), 'utf-8', function(err, page) {
           res.writeHead(404, {'Content-Type': 'text/html'});
           res.write(page);
           res.end();
         });
       } else {
         if (req.accepts('json')) {
           // Respond with json.
           res.status(404).send({ error: 'Not found' });
         } else {
           // Default to plain-text. send()
           res.status(404).type('txt').send('Not found');
         }
       }
     }

Basically instead of showing a NotFound component on the client (with a soft 404), I'm serving a NotFound page directly from the server (with a 404 status).



来源:https://stackoverflow.com/questions/42237527/send-both-404-status-and-redirect-to-404-component-in-react-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!