I'm building a REST API using node.js/Express.
I have some middleware applied to certain routes. I have a JavaScript syntax error which I can't resolve.
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
I need to be able to pass an array of roles to middleware2. E.g.
router.get('/watchdog', middleware, middleware2(...['ordinary','supervisor']), watchdogController.ping)
But this syntax fails :(
node server.js results in:
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)
This works:
router.get('/watchdog', middleware, middleware2, watchdogController.ping)
But now I can't see any roles in middleware2 ;( I need to be able to view the roles array in the middleware2 function.
I can't figure out what syntax to use... Can you guys help?
getis a middleware, you can create that middleware however you want. The easiest would be to create a function that returns your middleware--and you'd pass your roles into the middleware creator function.middleware2with:(req,res,next) => { middleware2(req,res,next,['ordinary','supervisor']) }. I thought I could use the spread operator, but not sure how to...createMiddleware2 = roles => { return function (req, res, next) { doSomethingWithRolesEtc... } }