I am working on a MEAN project where we have some defined api routes like this:
//products.controller.js
var express = require('express');
var router = express.Router();
const m = require('../../middlewares');
router.get('/products', [m.functionA, m.functionB, m.functionC], getProducts);
router.post('/products', [m.functionA, m.functionB, m.functionC], addNewProduct);
module.exports = router;
function getProducts(req, res) {
//code
}
function addNewProduct(req, res) {
//code
}
..............
//middlewares.js
function functionA(req, res, next) {
//code
}
function functionB(req, res, next) {
//code
}
function functionC(req, res, next) {
//code
}
Here now I can access req, res and next. How can I pass custom parameters to these middleware functions?
I looked over some SO questions and other articles and found that I can do like this:
[m.functionA('data'), m.functionB('data'), m.functionC('data')]
But on doing this, I get error that req, res are not defined.
Can anyone please help/suggest how to implement this. Let me know if any other details need to be added here.
If you want to use m.functionA('data')
, a common paradigm amongst Express middleware is to create a function that takes the parameter as an argument, and returns a middleware function:
function functionA(customParameter) {
return function(req, res, next) {
// code
}
}
The inner function (the one being returned) has access to customParameter
as well as req/res/next
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With