代码之家  ›  专栏  ›  技术社区  ›  Ramu

express路由器中间件中带有附加参数的函数数组

  •  0
  • Ramu  · 技术社区  · 2 年前
    const cb0 = function (data, req, res, next) {
      console.log('CB0')
      next()
    }
    
    const cb1 = function (data, req, res, next) {
      console.log('CB1')
      next()
    }
    
    app.get('/example/d', [cb0, cb1], (req, res, next) => {
      console.log('the response will be sent by the next function ...')
      next()
    }, (req, res) => {
      res.send('Hello from D!')
    })
    
    

    从上面的代码中,我传递了一个函数数组 [cb0, cb1] 每个功能都需要一些 data 类型属性 any 以及其他参数,如 req , res next .

    之前,我尝试使用以下格式传递数据属性 bind 概念 app.get('/example/d', [cb0.bind(data), cb1.bind(data)], (req, res, next)

    但如果我使用 绑定 概念,然后如何传递其他必需的属性( 请求 , 物件 下一个 )? 是否有其他方法传递所有参数,包括 数据 没有束缚?或者我们在express中使用函数数组有任何限制吗?

    1 回复  |  直到 2 年前
        1
  •  0
  •   T.J. Crowder    2 年前

    首先,你使用了 bind 错误(关于函数的编写方式):绑定的第一个参数是要用作 this 调用函数时;只有后续的参数定义了调用函数时的参数。所以你想要 cb0.bind(null, data) 而不是 cb0.bind(data) .

    但如果我使用 绑定 概念,然后如何传递其他必需的属性( req , res next )?

    (它们是参数,不是属性。)Express在调用函数时会执行此操作。这些参数将跟随您通过“烘焙”到函数中的参数 绑定 .您的功能已正确设置以处理该订单( data , 请求 , 物件 , 下一个 ),所以有了变化,你应该准备好出发了。

    所以:

    app.get('/example/d', [cb0.bind(null, data), cb1.bind(null, data)], (req, res, next) => {
        // ...
    

    为了清楚起见,下面是一个函数示例,其中数据通过 绑定 被称为进一步的论点:

    function example(data, other) {
        console.log(`data = ${JSON.stringify(data)}, other = ${JSON.stringify(other)}`);
    }
    
    const ex = example.bind(null, "baked in arg");
    
    // Emulating Express calling the middleware:
    ex("passed arg");

    旁注:您不必将中间件函数放入数组中,express对它们作为离散参数很满意:

    app.get('/example/d', cb0.bind(null, data), cb1.bind(null, data), (req, res, next) => {
        // ...
    

    两种方式都可以。