当然,您可以使用beforeRemote 挂钩来修改ctx.args 属性。此属性是远程方法(即自定义或内置)的输入。这样,您可以在该属性内复制一部分请求,并将其传递给内置方法
示例1与内置方法findOne。
MyModel.beforeRemote('findOne', function (ctx, model, next) {
ctx.args.filter.extrafield = ctx.req.headers['some-header'];
next();
});
然后override findOne 方法,因为这是你想要做的
MyModel.on('dataSourceAttached', function(obj){
var findOne = MyModel.findOne;
MyModel.findOne = function(filter, cb) {
console.log(filter.extrafield); // Print what was in the header
return findOne.apply(this, arguments);
};
});
最后用 curl 调用方法
curl -H "some-header: 'hello, world!'" localhost:3000/api/MyModel/findOne
示例 2 带有自定义遥控器 printToken,帮助您进一步了解
MyModel.beforeRemote('printToken', function (ctx, model, next) {
ctx.args.token = ctx.req.headers['some-header'];
next();
});
MyModel.printToken = function(token, cb) {
console.log(token);
cb();
}
MyModel.remoteMethod(
'printToken',
{
accepts: {arg: 'token', type: 'string', optional: true}
}
);
然后用 curl 调用远程,并传递预期的 header
curl -H "some-header: 'hello, world!'" localhost:3000/api/MyModel/printToken
编辑:有一个更简单的解决方案,仅适用于自定义遥控器
在定义远程方法时,可以告诉 loopback 将 http 请求的元素直接作为输入参数传递给远程
MyModel.remoteMethod(
'printToken',
{
accepts: [
{arg: 'req', type: 'object', 'http': {source: 'req'}},
{arg: 'res', type: 'object', 'http': {source: 'res'}}
]
}
);
这样,您的遥控器可以访问 req 和 res 对象。这是记录在here