发送 404 状态并重定向到 react-router 中的 404 组件 [英] Send both 404 status and redirect to 404 component in react-router
问题描述
我有一个带有 NotFound 组件的 react-router 3.0.0 设置,我显示为备用:
I have a react-router 3.0.0 setup with a NotFound component I'm showing as a fallback:
<Route component={NotFound} path="*"/>
然而,这会返回一个重定向,并且谷歌爬虫抱怨软 404.我可以重定向到我的 NotFound 组件并发送 404,类似于 Github 所做的吗?我从这里尝试了以下建议:如何让反应路由器以 404 状态代码响应?
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}/>
但这只是给了我一个 404 而不显示组件.
But that just gives me a 404 without displaying the component.
如何才能实现上述目标?
How can the above be accomplished?
推荐答案
只是为了结束这个循环 - 我不想走服务器端渲染路线,所以我在我的全局错误处理程序中间件中实现了以下内容:
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');
}
}
}
基本上,我没有在客户端显示 NotFound
组件(带有软 404),而是直接从服务器提供 NotFound 页面(带有 404 状态).
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).
这篇关于发送 404 状态并重定向到 react-router 中的 404 组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!