我有一个同构 react 应用程序,我想以某种方式在快速中间件之间传递状态。
我有以下处理表单提交的快速路由:
export const createPaymentHandler = async (req: Request, res: Response, next: NextFunction) => {
const { field } = req.body;
if (!paymentType) {
res.locals.syncErrors = { field: 'some error.' };
next();
return;
}
try {
const { redirectUrl } = await makeRequest<CreatePaymentRequest, CreatePaymentResponse>({
body: { paymentType },
method: HttpMethod.POST
});
res.redirect(redirectUrl);
} catch (err) {
error(err);
res.locals.serverError = true;
next();
}
};
下一个中间件正在处理渲染。
目前我正在使用 res.locals
,有没有更好的方法或公认的模式?
最佳答案
因为您的处理程序是异步的,您需要将 err
传递给 next
,如下所示:
next(err);
为了让您的中间件处理错误,而不是被默认错误处理程序拾取,您需要有四个参数:
app.use((err, req, res, next) => {
// handle the error
})
另外值得注意的是,错误处理程序需要在其他中间件之后指定。对于您的情况,将正常的“成功”中间件与错误处理程序一起使用可能是有意义的,而不是将两者组合成一个中间件。
最后,请记住,将 err
作为参数传递是特定于错误处理程序的。如果你只是想将一些数据传递到你的下一个中间件,你可以通过修改 req
:
req.x = 'some data'
next()
那么,下一个中间件的req
参数就会有你设置的数据了。
延伸阅读:https://expressjs.com/en/guide/using-middleware.html#middleware.error-handling
关于javascript - 在同构 react 应用程序中的快速中间件之间传递状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51863030/