【问题标题】:How to pass arguments to a callback function in express?如何将参数传递给express中的回调函数?
【发布时间】:2021-08-06 09:48:32
【问题描述】:

我在 NodeJS 中使用 express 中间件。我组织了我的路由没有回调,但是对于其中一些最好是互惠函数,所以我开始写一些回调。

我有例如这个函数(我没有放整个代码,在这里对我的问题没用):

async function verification(req, res, next) {

我在路由部分这样使用它:

router.post('/item/:id/dosomething',
  verification,
  async (req, res) => {

一切正常,但如果我想继续使用回调(有时它是一个干净高效的代码的好解决方案),我必须将一些参数传递给函数。当然我试过了,但它没有用:

router.post('/item/:id/dosomething',
  verification(arg1, arg2),
  async (req, res) => {

我在 StackOverflow 上搜索了“将参数传递给回调函数”的答案,但少数有趣的人谈到了包装函数,我认为我无法实现。

如果有人能帮我一把,那就太好了。谢谢:)


这是一个关于 next 如何在没有在调用中写入它的情况下工作的 sn-p(查看 verif):

回调:

async function verif(req, res, next) {
  let rows;
  const {
    id
  } = req.params;
  ({ rows } = await db.query(`XXX`))
  if (rows.length === 1) {
    return next();
  } else {
    retour(req, res, 500, "No can do.");
  }

名称:

router.post('/mymusic/:id/addElements',
  droits.verifRightsCB.bind(undefined, 'music', 'addInMyMusic'),
  verif,
  async (req, res) => {...

路由的最后一部分(async (req, res) =>)只有在next()条件在verif中满足时才会执行,虽然我没有传递任何参数。

【问题讨论】:

    标签: express routes callback


    【解决方案1】:
    function verification(arg1, arg2, req, res, next) {...}
    router.post('/item/:id/dosomething',
      verification.bind(undefined, arg1, arg2),
      (req, res) => {...}
    

    (函数不必是async。)

    请注意,router.post 语句是在服务器启动期间执行的,而不是每个请求。因此你不能写类似

    router.post('/item/:id/dosomething',
      verification.bind(undefined, arg1, req.params.arg),
      (req, res) => {...}
    

    因为在服务器启动期间没有req。相反,你可以写

    router.post('/item/:id/dosomething',
      (req, res, next) => verification(arg1, req.params.arg, req, res, next),
      (req, res) => {...}
    

    verification 函数然后可以

    • 验证成功后调用next()调用其他中间件函数((req, res) => {...})
    • 或在验证错误后调用next(err),以跳过其他中间件功能并报告错误。

    【讨论】:

    • 感谢您的回答,但我不明白为什么这些函数不必是async。我每个人都有await,所以我必须输入async
    • 异步函数是返回 Promise 的函数。 Express 中间件函数不返回任何内容,因此是否将它们声明为异步并不重要。中间件函数调用next() 以便将控制权传递给下一个中间件函数,这是它们实现异步的方式。
    • @djcaesar9114 您不能在router.post 中使用req,因为当时没有req。请参阅我的增强答案。
    • @djcaesar9114 你以前怎么能用next?能贴一下代码sn-p吗?
    • 中间件verif等价于中间件(req, res, next) => verif(req, res, next)。但是填充verification函数的额外参数arg1args2需要长版本(req, res, next) => verification(arg1, req.params.arg, req, res, next)
    猜你喜欢
    • 2013-02-07
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2012-02-08
    • 1970-01-01
    相关资源
    最近更新 更多