Loopback 中间件 - 如何访问 req 对象中的数据?

Loopback middleware - how to access data in req object?

我刚开始使用 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();
});

部分middleware.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"}

我想在请求中添加键值对。怎么做到的?

原来我们只能通过req对象的Readable.read()方法读取请求消息,它是http.IncomingMessageclass的一个实例(如reference 中提到的)。而且(对我来说)似乎不可能修改消息。如果我们必须以任何方式操作请求消息,则不会通过 req 对象来完成。正如@IvanSchwarz 所提到的,通常是在其他步骤中执行此操作,例如在将其存储到数据库之前,将消息传递给任何方法等

感谢您的帮助:)