Sagar Mahajan Sagar Mahajan - 3 months ago 20
Node.js Question

Passing parameters to router middleware function

I want to create the generic middleware which will validate the data,

My question is how I can send additional parameters to middleware (i.e. validateRequest) , additional parameters which I want to send is useful to determine which fields need to be validated.

Below is the sample code for understanding.

var express = require('express');
var router = express.Router();
var users = require('./controllers/users.js');

router.post('/api/v1/user/', validateRequest, users.create);

function validateRequest(req,res, next){

}

module.exports = router;

Answer

try

var express = require('express');
var router = express.Router();
var users = require('./controllers/users.js');

router.post('/api/v1/user/', validateRequest(['field1', 'field2']), users.create);

function validateRequest(fields){
    var middleware = function (req,res, next) {
        // code goes here
    }
    return middleware;
}

module.exports = router;