Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 当一个值通过下一个函数时,它意味着什么?_Node.js_Express - Fatal编程技术网

Node.js 当一个值通过下一个函数时,它意味着什么?

Node.js 当一个值通过下一个函数时,它意味着什么?,node.js,express,Node.js,Express,我一直在网上浏览一些代码,以构建一个使用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,

我一直在网上浏览一些代码,以构建一个使用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()”函数,但这段代码有一个值,一个对象,它被传递到下一个函数中


这意味着什么?

这似乎是Node.js中的命名约定,用于控制下一个匹配路由

这些东西很常见,也很方便,主要用于访问检查或通配符路由。(/user/:id)


从express文档中:

从Express5开始,返回承诺的中间件函数在拒绝或抛出错误时将调用next(值)。next将使用拒绝的值或抛出的错误调用

在我看来,next()函数中的值就是发送给下一个回调函数的返回值。通常,您不希望发送自定义值,而只是转到下一个中间件函数,但是在这种情况下,他们显然希望在next()函数中设置错误消息,从而覆盖任何默认值

希望这有帮助

这段代码有一个值,一个对象,它被传递到下一个函数中。这是什么意思? Ans:这意味着将对象作为参数传递给下一个中间件函数

app.use((err,req,res,next)=>{
返回res.status(err.status | | 400).json({
状态:err.status | | 400,
消息:err.message | |“处理请求时出错”
});
});
此处err参数是您传递的对象


希望这有帮助

如果这是一个用于控制下一个匹配路由的命名约定,那么我的示例中的“status”和“message”值在做什么?示例中的“status”和“message”是请求对象,在“status”中设置响应代码,在“message”中设置其消息。因此,next()仍然会将您转发到路由,但会为您提供此响应对象,这将阻止用户查看路由内容
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();
    }
  }