Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 530
Aman Gupta Avatar asked Jan 30 '23 14:01

Aman Gupta


1 Answers

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.

like image 142
robertklep Avatar answered Feb 02 '23 03:02

robertklep