Popatop15 Popatop15 - 3 months ago 22
Javascript Question

Providing Custom Params In Express Middleware

I am having a problem with my Node.js app. In short I want to pass custom parameters into my middleware function other than just

req
,
res
, and
next
.

Middleware file:

var DB = require('./DB.js');

function requirePermissions(e) {
console.log('nope')
}

module.exports = requirePermissions;


Route:

router.post('/posts', requirePermissions('post_creation'), function(req, res) {
var o = req.body,
title = o.post.title,
content = o.post.content;

res.send('made it');
});


I have confirmed that using function
requirePermissions(req, res, next) {}
will work, but I do not understand how to include my own parameters.

Answer

Your function requirePermissions should return another function which will be the actual middleware:

function requirePermissions(e) {
  if (e === 'post_creation') {
    return function(req, res, next) {
      // the actual middleware
    }
  } else if (e === 'something_else') {
    return function(req, res, next) {
      // do something else
    }
  }
}

You can also do it like that:

function requirePermissions(e) {
  return function(req, res, next) {
    if ('session' in req) {
      if (e === 'post_creation') {
        // do something
      } else if (e === 'something_else') {
        // do something else
      }
    }
  }
}
Comments