Charles L.
Charles L.

Reputation: 1970

Using express middle ware and passing res.local data to routes

I am trying to set up a securitycheck middleware that will run on the routes i add it to.

Middleware

function SecurityCheckHelper(req, res, next){
  apiKey = req.query.apiKey;
  security.securityCheck(apiKey).then(function(result) {
      res.locals.Security = result.securitycheck;
      console.log(res.locals.Security);
  });
  return next(); // go to routes

};

Route

app.get('/settings', SecurityCheckHelper,function(req, res, next) {
  console.log(res.locals);
});

Its relatively straight forward I'm trying to pass result.securitycheck (which return true/false) into the /settings route. However res.locals is returning an empty object

Upvotes: 1

Views: 310

Answers (2)

Anand
Anand

Reputation: 1355

You need to interface security check promise with the callback.

function SecurityCheckHelper(req, res, next){
  apiKey = req.query.apiKey;
  security.securityCheck(apiKey)
  .then(function(result) {
      res.locals.Security = result.securitycheck;
      console.log(res.locals.Security);
      return next();
  })
  .catch(err => next(err));
};

Upvotes: 1

Keith
Keith

Reputation: 24241

Your calling next before you have run your securityCheck.

IOW: the next middleware is getting processed before you securityCheck has finished processing. securityCheck is async,.

Placing your next inside your then, will wait until the securityCheck has finished.

eg.

function SecurityCheckHelper(req, res, next){
  apiKey = req.query.apiKey;
  security.securityCheck(apiKey).then(function(result) {
      res.locals.Security = result.securitycheck;
      console.log(res.locals.Security);
      next();
  });
};

Upvotes: 1

Related Questions