next() 在 Express 中接受哪些参数

What parameters does next() take in Express

由于 Express.js,我目前正在构建一个 API,但我仍然无法相信它有多么神奇。我弄清楚了如何使用中间件,处理请求和响应,如何转到下一个中​​间件......但是有件事很触发我,那就是 next().

我知道next()是什么,只是想不通next()可以接受什么样的参数,以及它们会做什么。一开始我以为是给下一个中间件传数据,原来我错了,这里有req.locals

有人能给我讲讲吗?

您可以选择三种方式调用next():

1.继续路由。如果你只是想继续路由到链中匹配这条路由的下一个路由处理程序,那么你只需要不带参数调用它:

next();

这个在中间件中最常用:

app.use((req, res, next) => {
    // set an item in the session and then continue routing
    req.session.xxx = "foo";
    next();
});

2。将错误中止路由到您的集中式错误处理程序。 如果您想设置错误并让路由跳到您的通用错误处理程序,那么您可以传递一个错误:

next(new Error("timeout contacting database"));

然后这将调用您的通用错误处理路由并将特定错误传递给它,您的通用错误处理代码可以在其中决定要做什么。这允许您将错误处理响应代码集中在一个地方。使用 next(err) 的示例是 here.

您可以查看 the doc for generalized error handling in Express 了解其工作原理的示例。

3。跳过此路由器中的路由处理程序,继续在其他路由器中路由。 如果您想跳过当前路由器中的所有路由处理程序,但继续使用可能已注册的任何其他路由,那么您可以这样做:

next('route');

来自文档:

You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke next('route') to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.

如果您在 this page of the doc, you will find lots of examples. There's an example of this usage here in the doc 上重复搜索 "next("。


仅供参考,Express 5 可能会为 next() 添加一些新用途,因为它可能 return 承诺让您知道路由现在何时完全完成。