reactjs – 发送404状态并重定向到react-router中的404组件
发布时间:2020-12-15 20:30:10 所属栏目:百科 来源:网络整理
导读:我有一个带有NotFound组件的react-router 3.0.0设置,我将其作为后备显示: Route component={NotFound} path="*"/ 但是,这会返回重定向,Google抓取工具会抱怨软404.我可以重定向到我的NotFound组件并发送404,类似于Github的例子吗?我从这里尝试了以下建议:
我有一个带有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而没有显示组件. 如何实现上述目标? 解决方法
只是关闭这个循环 – 我不想去服务器端渲染路由,所以我在我的全局错误处理程序中间件中实现了以下内容:
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状态). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |