我正在将Loopback用作第三方API的API接口。 我正在尝试通过回送中的远程方法调用第三方API的方法。
在没有环回的情况下,成功调用第三方方法的方法如下:
public static double cosine(double x, int k) {
double cosineresult = 0;
double cosinedenominator = 1; // initial value 0! = 1; overflows at k = 86
int j = 2; // next multiplier in denominator factorial (skip 1)
for (int i = 0; i <= k; i++) {
double cosinenumerator = Math.pow((-1),i) * Math.pow(x, (2 * i));
// Continue calculation of factorial from last value
while (j <= 2 * i) {
cosinedenominator *= j++;
}
cosineresult += cosinenumerator / cosinedenominator;
}
return cosineresult;
}
使用Loopback,我有一个数据源,如下所示:
curl -X POST --header 'Content-Type: application/json' --header 'Accept: */*' --header 'authorization: Bearer eyJhbGciOiJIUzUxMiJ9....' -d '{ \
"attr1":"123", \
"attr2":"456" \
}' 'http://third-party-host/plugins/aca74a80/'
,然后是类似以下的模型代码:
{
...
"APIDataSource": {
"name":"APIDataSource",
"crud": false,
"connector": "rest",
"operations": [
{
"functions": {
"saveEntityAttributes": ["entityId", "mrequest", "authkey"]
},
"template": {
"method": "POST",
"url": "http://third-party-host/plugins/{entityId}",
"headers": {
"authorization":"Bearer {authkey}"
},
"json":"{mrequest}"
}
}
]
}
}
这将引发错误:“请求不是json”很有意义,因为生成的“ json”内容是“ entityID”参数,而不是预期的“ mrequest”参数(其中包含json:“ {” attr1“:” 123“,” attr2“:” 456“}”),如回送日志所示:
'use strict';
module.exports = function(Model) {
Model.saveEntityAttributes = function(req, cb) {
Model.app.models.MyAPI.saveEntityAttributes(req)
.then(result => {
console.log(result);
cb(null, result);
})
}
Model.remoteMethod (
'saveEntityAttributes',
{
http: {path: '/saveentityattributes', verb: 'post'},
accepts: [ {arg: 'req', type: 'object', http: { source: 'req' } }],
returns: {root: true}
}
);
};
我的问题是如何将“ mrequest”内容带入“ json”正文,而不是当前的“ entityId”内容?
欢迎任何建议。谢谢!
答案 0 :(得分:0)
我已经解决了这个问题!
在数据源中,“ json”选项必须替换为: “ body”:“ {mrequest:object}”
然后,在模型代码中,必须将远程方法的当前“ req” http源替换为:“ query”
然后,回送日志显示正确的请求调用:
loopback:connector:rest Request: {"method":"POST","uri":"http://third-party-host/plugins/aca74a80","json":true,"headers":{"authorization":"Bearer eyJhbGciOiJIUzUxMiJ9..."},"body":{"art1":"1qa","atr2":"2ws"}} +0ms