djcaesar9114
djcaesar9114

Reputation: 2137

How to pass arguments to a callback function in express?

I'm using express middleware with NodeJS. I organized my routes with no callbacks, but for some of them it's better to mutualize functions, so I began to write some callbacks.

I have for example this function (I don't put the whole code, it's useless for my question here):

async function verification(req, res, next) {

And I use it like this in the route part:

router.post('/item/:id/dosomething',
  verification,
  async (req, res) => {

Everything works well, but if I want to continue using callbacks (sometimes it's a good solution to have a clean and efficient code), I'll have to pass some arguments to the function. Of course I tried this, and it didn't work:

router.post('/item/:id/dosomething',
  verification(arg1, arg2),
  async (req, res) => {

I searched on StackOverflow answers for "pass arguments to a callback function" but the few that could be interesting talked about a wrapping function, which I don't think I can implement in my case.

If anybody could give me a hand, that would be great. Thanks :)


Here is a snippet of how a next worked without writing it in the call (look at the verif):

The callback:

async function verif(req, res, next) {
  let rows;
  const {
    id
  } = req.params;
  ({ rows } = await db.query(`XXX`))
  if (rows.length === 1) {
    return next();
  } else {
    retour(req, res, 500, "No can do.");
  }

Where it's called:

router.post('/mymusic/:id/addElements',
  droits.verifRightsCB.bind(undefined, 'music', 'addInMyMusic'),
  verif,
  async (req, res) => {...

The last part of the route (async (req, res) =>) is only executed when the next() condition is fulfilled in the verif, although I didn't pass any argument.

Upvotes: 2

Views: 1305

Answers (1)

Heiko Theißen
Heiko Theißen

Reputation: 17452

function verification(arg1, arg2, req, res, next) {...}
router.post('/item/:id/dosomething',
  verification.bind(undefined, arg1, arg2),
  (req, res) => {...}

(The functions need not be async.)

Note that the router.post statement is executed during server start-up, not per request. Therefore you cannot write something like

router.post('/item/:id/dosomething',
  verification.bind(undefined, arg1, req.params.arg),
  (req, res) => {...}

because there is no req during server start-up. Instead, you may write

router.post('/item/:id/dosomething',
  (req, res, next) => verification(arg1, req.params.arg, req, res, next),
  (req, res) => {...}

The verification function can then

  • call next() after successful verification to invoke the other middleware function ((req, res) => {...})
  • or call next(err) after a verification error in order to skip the other middleware function and report the error.

Upvotes: 2

Related Questions