How to send parameters to the middleware functions in Express routing?

Viewed 4158

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.

2 Answers
Related