2016-04-22 27 views
0

我剛剛開始使用Loopback API框架,並且希望定義一箇中間件,在將它傳遞到下一個函數之前,它會預處理req數據。但我不知道如何訪問req對象中的數據。任何幫助?環回中間件 - 如何訪問req對象中的數據?

E.g.

function middleWareThatAddAPropertyToTheRequestJSON(req, res, next) { 
    // Of course I get undefined for req.data, but that's approximately what I want. 
    req.data.somethingIWouldLikeToChange = "blahblahblah"; 
} 

編輯:

這就是我創建的應用程序(在server.js)的middleware.json的

var loopback = require('loopback'); 
var boot = require('loopback-boot'); 

var app = module.exports = loopback(); 

app.start = function() { 
    // start the web server 
    return app.listen(function() { 
    app.emit('started'); 
    var baseUrl = app.get('url').replace(/\/$/, ''); 
    console.log('Web server listening at: %s', baseUrl); 
    if (app.get('loopback-component-explorer')) { 
     var explorerPath = app.get('loopback-component-explorer').mountPath; 
     console.log('Browse your REST API at %s%s', baseUrl, explorerPath); 
    } 
    }); 
}; 

// Bootstrap the application, configure models, datasources and middleware. 
// Sub-apps like REST API are mounted via boot scripts. 
boot(app, __dirname, function(err) { 
    if (err) throw err; 

    // start the server if `$ node server.js` 
    if (require.main === module) 
    app.start(); 
}); 

部分(與server.js相同的目錄)

... 
"initial": { 
... 
    "./middleware/rest/middlewareThatAddAPropertyToTheRequestJSON": {} 
}, 
... 

中間件/其他/中間件ThatAddAPropertyToTheRequestJSON.js:

module.exports = function() { 
    return function middlewareThatAddAPropertyToTheRequestJSON(req, res, next) { 
     // TODO: add sth to the req 
     next(); 
    }; 
}; 

另一個編輯:

也許我不是精確的。我想修改一個POST請求。

例如客戶訊息:

{「一個」:「B」}

欲一個鍵 - 值對添加到請求。如何做呢?

回答

0

事實證明,我們只能通過req對象,它是http.IncomingMessage類的一個實例的Readable.read()方法讀出的請求消息(如在reference提到的)。而且對我來說,似乎不可能修改該消息。如果我們不得不操縱請求消息,則不會通過req對象完成。正如@IvanSchwarz所提到的那樣,通常情況下在其他步驟中這樣做。在將其存儲到數據庫之前,將消息傳遞給任何方法等。

感謝您的幫助:)

相關問題