发送404状态并重定向到react-router中的404组件

时间:2017-02-14 22:36:45

标签: reactjs react-router react-router-component react-routing

我有一个带有NotFound组件的react-router 3.0.0设置我显示为后备:

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

然而,这会返回重定向,Google抓取工具会抱怨软404。我可以重定向到我的NotFound组件并发送404,类似于Github的例子吗?我从这里尝试了以下建议:How to let react router respond with 404 status code?

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

但是这只是给了我404而没有显示组件。

如何完成上述工作?

1 个答案:

答案 0 :(得分:1)

只是关闭这个循环 - 我不想去服务器端渲染路由,所以我在我的全局错误处理程序中间件中实现了以下内容:

     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');
         }
       }
     }

基本上不是在客户端上显示NotFound组件(使用软404),而是直接从服务器提供NotFound页面(具有404状态)。