簡體   English   中英

從Express JS中間件返回值

[英]Return a value from express js middleware

下面的代碼是我明確的中間件調用

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

console.log(c);

//中間件功能

module.exports = function() {

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

};

在上面的代碼console.log打印控制台中,一旦應用程序啟動。

我想將中間件的值返回/傳遞給我的快速應用程序。 請任何建議嗎?

設置任何您想在請求范圍內使用的要求對象。

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

然后可以在請求處理程序中使用它:

app.get('/test', function(req, res){
  console.log(req.b);
});

應該這樣做:

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

//中間件功能

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

或這個:

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

//中間件功能

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!',
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM