我一直在网上浏览一些代码,以便构建一个使用Express后端的React to-do应用程序。 网站的链接在这里,我碰到了这部分代码:
app.get("/todos", async (req, res, next) => {
try {
const todos = await db.Todo.find({});
return success(res, todos);
} catch (err) {
next({ status: 400, message: "failed to get todos" });
}
});
我知道下一个函数是将它所在的当前中间件函数的操作传递给同一路由的下一个中间件函数的函数。 然而,在线源代码只是使用简单的“next()”函数,但这段代码有一个值,即一个对象,它传递到下一个函数中。
这是什么意思?
Ans:这意味着您正在将一个对象作为参数传递给下一个中间件函数。
app.use((err, req, res, next) => {
return res.status(err.status || 400).json({
status: err.status || 400,
message: err.message || "there was an error processing request"
});
});
这里,err参数是要传递的对象。
希望这有帮助
它似乎是Node.js中的一个命名约定,用于控制下一个匹配路由。
这些东西经常被发现,也非常方便,并且主要用于访问检查或通配符路由。 (/user/:id)
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
// this route requires auth, check if logged in. If not, redirect to login.
if (!store.getters.isLoggedIn) {
next({
path: `/${ViewName.UserLogin}`,
query: { redirect: to.fullPath }
});
} else {
next();
}
}
在express文档中:
从Express 5开始,返回承诺的中间件函数在拒绝或抛出错误时将调用next(值)。 将使用被拒绝的值或抛出的错误调用next。
因此,在我看来,next()函数中的值是发送到下一个回调的返回值。 通常,您不希望发送自定义值,而只是转到下一个中间件函数,但是在本例中,他们显然希望在next()函数中设置错误消息,从而覆盖任何默认值。
希望这有帮助