我正在使用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)
但是现在我看不到middleware2中的任何角色;(我需要能够查看
middleware2
函数中的角色数组。我不知道该使用什么语法...你们可以帮忙吗?
最佳答案
解决方案(感谢@DaveNewton):
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 = roles => function(req, res, next) {
console.log('middleware2')
console.log(roles)
next()
}
router.get('/watchdog', middleware, middleware2(['ordinary','supervisor']), watchdogController.ping)
module.exports = router