简体   繁体   中英

Express app.param() middleware fires multiple times per request

I've supplied my Express 4 app with some middleware to fire every time a particular set of parameters shows up in a request like so:

app.param(['mystic', 'donkey', 'toadstool'], function(req, res, next, param) {
  console.log(req.params);
});

Unfortunately if I visit GET /:mystic/:donkey/:toadstool . It prints out:

{ mystic: x, donkey: y, toadstool: z }
{ mystic: x, donkey: y, toadstool: z }
{ mystic: x, donkey: y, toadstool: z }

When all I want is just:

{ mystic: x, donkey: y, toadstool: z }

Is there a way to stop it from firing multiple times per req/response and still use an array at the first parameter to app.param ?

if you see in the source code of app.param , you will realize that for every param in the array you put: ['mystic', 'donkey', 'toadstool'] , the callback you bind to app.param it will be called sequentially, in this case three times.

So there is no way you could do to have all the values in once invocation of app.param , probably you could grab all your params one at a time, something like:

var express = require('express');
var app = express();

app.param('mystic', function(req, res, next, mystic) {
  console.log('mystic: %s', mystic);
  next();
});

app.param('donkey', function(req, res, next, donkey) {
  console.log('donkey: %s', donkey);
  next();
});

app.param('toadstool', function(req, res, next, toadstool) {
  console.log('toadstool: %s', toadstool);
  next();
});

app.get('/:mystic/:donkey/:toadstool', function(req, res) {
  res.send('hey');
});

app.listen(4040, function() {
  console.log('server up and running');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM