在同构反应应用程序中的快速中间件之间传递状态

dag*_*da1 8 javascript node.js express reactjs

我有一个同构反应应用程序,我想以某种方式在快速中间件之间传递状态.

我有以下处理表单提交的快递路线:

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();
  }
};
Run Code Online (Sandbox Code Playgroud)

下一个中间件正在处理渲染.

在我使用的那一刻res.locals,是否有更好的方式或公认的模式?

Luk*_*uke 2

因为您的处理程序是异步的,所以您需要将其传递errnext,如下所示:

next(err);
Run Code Online (Sandbox Code Playgroud)

为了让您的中间件处理错误,而不是由默认错误处理程序拾取错误,您需要有四个参数:

app.use((err, req, res, next) => {
  // handle the error
})
Run Code Online (Sandbox Code Playgroud)

还值得注意的是,错误处理程序需要在其他中间件之后指定。对于您的情况,将正常的“成功”中间件与错误处理程序一起使用可能是有意义的,而不是将两者组合成一个中间件。

最后,请记住,err作为参数传递是特定于错误处理程序的。如果您只想将一些数据传递到下一个中​​间件中,您可以通过修改以下内容来实现req

req.x = 'some data'
next()
Run Code Online (Sandbox Code Playgroud)

然后,下一个中间件的req参数将具有您设置的数据。


进一步阅读:https://expressjs.com/en/guide/using-middleware.html#middleware.error-handling