【发布时间】:2016-04-22 06:21:27
【问题描述】:
我刚刚开始使用 Loopback API 框架,并想定义一个中间件,在将请求数据传递给下一个函数之前对其进行预处理。但我不知道如何访问req 对象中的数据。有什么帮助吗?
例如
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 中)
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();
});
中间件.json的一部分(与server.js在同一目录下)
...
"initial": {
...
"./middleware/rest/middlewareThatAddAPropertyToTheRequestJSON": {}
},
...
middleware/rest/middlewareThatAddAPropertyToTheRequestJSON.js:
module.exports = function() {
return function middlewareThatAddAPropertyToTheRequestJSON(req, res, next) {
// TODO: add sth to the req
next();
};
};
另一个编辑:
也许我说得不准确。我想修改一个 POST 请求。
例如客户帖子:
{"a": "b"}
我想在请求中添加一个键值对。怎么办?
【问题讨论】:
标签: node.js loopbackjs