ThomasReggi
ThomasReggi

Reputation: 59345

Pass req variables from .param to .use?

The code below demonstrates trying to log req.hash_id from middleware. It's showing up for me as undefined. Is there anyway that I can get this to work? Or easily parse ":hash" out in regular .use middleware?

app.param("hash",function(req, res, next, id){
  req.hash_id = id;
  return next();
});

app.use(function(req, res, next){
  console.log(req.hash_id);
  return next();
});

Upvotes: 0

Views: 500

Answers (1)

zemirco
zemirco

Reputation: 16395

I don't think you can use req.params inside a middleware function as it is bound to specific routes. You could use req.query though, but then you have to write your routes differently, e.g. /user?hash=12345abc. Not sure about passing the value from app.param to app.use.

If you have a specific structure for your routes, like /user/:hash you could simply write

// that part is fine
app.param('hash',function(req, res, next, id){
  req.hash_id = id;
  return next();
});

app.all('/user/:hash', function(req, res, next) { // app.all instead app.use
  console.log(req.hash_id);
  next();  // continue to sending an answer or some html
});

// GET /user/steve -> steve

Upvotes: 2

Related Questions