gpt4 book ai didi

javascript - 如何让React路由器响应404状态码?

转载 作者:行者123 更新时间:2023-12-03 13:02:39 25 4
gpt4 key购买 nike

我以root身份使用react router,并且“/”下的所有请求都定向到react router。当React Router发现url与任何定义的组件不匹配时,它会使用NoMatch组件进行渲染。问题来了,NoMatch 被渲染了,这就是我想要的,但状态代码仍然是 200 而不是 404。当我的 css 或 js 文件放置有错误的 url 时, react 路由器会做同样的事情,它会响应 200 !然后页面告诉我,我的资源内容类型存在一些问题!

那么,我如何使用React Router来处理“/”中的所有内容,并且仍然让它正确处理404错误(以404状态代码响应)?

react 路由器中的代码

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

服务器端

  router.use('/', function(req, res, next) {
res.render('index-react', {
title: 'some title'
});
});

最佳答案

使用react-router 2.0.0你可以这样做:

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

编辑:

您需要做的是在路线定义上创建自定义属性,如上面所示(状态)。

当您要在服务器端渲染组件时,请检查此属性并使用此属性的代码发送响应:

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

服务器.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...
}
});
});

抱歉……我的解决方案本身无法正常工作,并且我错过了您实际检查此属性并相应渲染的正确代码段。

如您所见,我只是将“未找到”文本发送给客户端,但是,最好从 renderProps 捕获要渲染的组件(在本例中为 NoMatch)并渲染它。

干杯

关于javascript - 如何让React路由器响应404状态码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36052604/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com