我正在使用 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
我需要能够将一组 Angular 色传递给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 中看不到任何 Angular 色;(我需要能够在 middleware2
函数中查看 Angular 色数组。
我不知道该使用什么语法...你们能帮忙吗?
最佳答案
解决方案(感谢@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
关于javascript - node.js/JavaScript 语法 - 向传递的参数添加额外的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56130854/