Sami Boudoukha
Sami Boudoukha

Reputation: 599

How to pass data through middlewares using Loopback?

I'm actually using loopback, and here is my needs:

I have two middlewares triggered by a POST request on /api/Orders/, and I need middleware 1 to pass data to middleware 2.

For example:

middleware1.js

module.exports = function() {
    return function firstMiddleware(req, res, next) {
        var toPass= "string to pass to second middleware";
        next();
  };
}

middleware2.js

module.exports = function() {
    return function secondMiddleware(req, res, next) {
     //Do whatever to get passed value from middleware1
  };
}

I did not found anything useful in the official documentation talking about this, but I may have missed it.

Thanks.

Upvotes: 1

Views: 176

Answers (1)

michaelitoh
michaelitoh

Reputation: 2340

In middleware1 you can update req object and access the variable in the middleware2.

middleware1.js

module.exports = function() {
    return function firstMiddleware(req, res, next) {
        var toPass= "string to pass to second middleware";
        req.locals = { toPass };
        next();
  };
}

middleware2.js

module.exports = function() {
    return function secondMiddleware(req, res, next) {
    console.log(req.locals.toPass);
    next();
  };
}

Upvotes: 1

Related Questions