0

Below code is my express middleware call

var c = app.use(myMiddleware());

console.log(c);

// the middleware function

module.exports = function() {

    return function(req, res, next) {
       var b =  {'A' : 1};
        next();
    }

};

In above code console.log print console once application started.

I want to return/pass a value from middleware to my express application. please any suggestion?

2 Answers 2

2

Set anything you want to use in request scope to req object.

app.use(function(req, res, next) {
  var b =  {'A' : 1};
  req.b = b;
  next();
});

then you can use it in your request handler:

app.get('/test', function(req, res){
  console.log(req.b);
});
Sign up to request clarification or add additional context in comments.

3 Comments

I have edited my solution. Please check if it works.
app.get not working but if we use below code then it working app.use(function(req, res, next) { console.log("Middleware", req.b); });
yes your right but req.b is undefined when I request localhost:3000/test but app.use(function) is working when I request localhost:3000/ I am not understand what happening
0

This should do it:

var c = app.use(myMiddleware({
  callback: function(c) {
    console.log(c)
  }
}))

// the middleware function

module.exports = function(options) {
  return function(req, res, next) {
    var b =  {'A' : 1}
    next()
  }
}

Or this:

var x = myMiddleware()
var c = app.use(x.function)
console.log(x.something)

// the middleware function

module.exports = function(options) {
  options && options.callback && options.callback('Hello world!')

  return {
    function: function(req, res, next) {
      var b =  {'A' : 1}
      next()
    },
    something: 'Hello world!',
  }
}

1 Comment

Second example not work out for my need because 'Hello world' got print in app start. Need to get the value on request.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.