gpt4 book ai didi

javascript - React Router 服务器端的错误处理

转载 作者:行者123 更新时间:2023-12-03 06:48:28 25 4
gpt4 key购买 nike

我正在开发同构应用程序 react-router & express 。我在服务器端渲染中使用 react 路由器。我想要自定义错误页面,该页面将在服务器端错误、渲染错误或当然找不到时发送。但我在连接这些点时遇到了问题。这是我的路线:

<Route component={Index} path="/">
<IndexRoute component={Home} />
<Route component={Chart} path="chart" />
<Route component={Login} path="login" />
<Route component={Error} path="error" /> //path="*" takes care only for not found,
and it still sends the client a 200 status code
</Route>

这是我唯一的快速路线:

app.use((req, res, next) => {
const location = createLocation(req.url);
const css = [];
match({ routes, location }, (err, redirectLocation, renderProps) => {
if (err) {
//500 internal error
return next(err);
}
if(redirectLocation){
//react-router redirect, no problems here
return res.redirect(redirectLocation.path + redirectLocation.query);
}
if (!renderProps){
//404 not found
let error = new Error();
error.message = "Not Found";
error.status = 404;
return next(err);
}

res.status(200).end(getHtml(renderProps));
}
}

//...
//some regular express error handler to log in console and (as of right now) send simple text to client.

同时getHtml(renderProps)生成 html reactrenderToString()<RouterContext {...renderProps} /> .

我想以某种方式路由到错误组件,该组件将可以使用路由器上下文(或其他方式)访问错误代码,以便它显示适当的错误。

有什么想法吗?

最佳答案

我在服务器端渲染上找到了 404 状态的解决方案,

像这样配置路由:

<Route component={Index} path="/">
<IndexRoute component={Home} />
<Route component={Chart} path="chart" />
<Route component={Login} path="login" />
<Route component={Error} path="*" notFound />
</Route>

并设置快速路线如下:

app.use((req, res, next) => {
const location = createLocation(req.url);
const css = [];
match({ routes, location }, (err, redirectLocation, renderProps) => {
if (err) {
//500 internal error
return next(err);
}
if(redirectLocation){
//react-router redirect, no problems here
return res.redirect(redirectLocation.path + redirectLocation.query);
}
if (!renderProps){
//404 not found
let error = new Error();
error.message = "Not Found";
error.status = 404;
return next(err);
}

const notFound = renderProps.routes.filter((route) => route.notFound).length > 0;
res.status(notFound ? 404 : 200);

res.end(getHtml(renderProps));
}
}

关于javascript - React Router 服务器端的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37613853/

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