node.js / JavaScript语法-在传递的参数中添加额外的参数

时间:2019-05-14 12:46:36

标签: javascript node.js syntax

我正在使用node.js / Express构建REST API。

我对某些路由应用了一些中间件。我有一个无法解决的JavaScript语法错误。

server.js

const express = require('express')
const router = express.Router()


const watchdogController = {
  ping: function(req, res, next) {
    console.log('watchdog')
    res.status(200).send('woof!')
    //next()
  }
}
const middleware = function(req, res, next) {
  console.log('middleware')
  next()
}
const middleware2 = function(req, res, next, roles) {
  console.log('middleware2')
  //console.log(roles)   //I want to be able to view the roles here!
  next()
}


//This line is where I have the issue...
router.get('/watchdog', middleware, middleware2, watchdogController.ping)



module.exports = router

我需要能够将一系列角色传递给middleware2。例如。

router.get('/watchdog', middleware, middleware2(...['ordinary','supervisor']), watchdogController.ping)

但是此语法失败:(

node server.js导致:

middleware2
undefined
/Users/asdf7/Desktop/asdf7/lib/router.js:19
  next()
  ^

TypeError: next is not a function
    at middleware2 (/Users/asdf7/Desktop/eoh/lib/router.js:19:3)
    at Object.<anonymous> (/Users/asdf7/Desktop/eoh/lib/router.js:26:37)
    at Module._compile (internal/modules/cjs/loader.js:701:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.<anonymous> (/Users/asdf7/Desktop/asdf7/index.js:2:16)

这有效:

router.get('/watchdog', middleware, middleware2, watchdogController.ping)

但是现在我在中间件2中看不到任何角色;(我需要能够在middleware2函数中查看角色数组。

我不知道该使用哪种语法...你们可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

解决方案(感谢@DaveNewton):

// Row.js
...
const { a, b, c } = props;
console.log(a, b, c); // 1 2 3    
// Or   
const { ...order } = props;
console.log(order); // { a: 1, b: 2, c: 3 }