strongloop - 环回休息连接器远程方法不起作用
问题描述
我使用 Loopback 作为第 3 方 API 的 API 接口。我正在尝试通过 Loopback 中的远程方法调用 3rd 方 API 的方法。
不使用 Loopback,成功调用 3rd 方方法的方式如下:
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/'
使用 Loopback,我有一个如下所示的数据源:
{
...
"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}"
}
}
]
}
}
然后是如下的模型代码:
'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}
}
);
};
这是抛出错误:“请求不是 json”,这是有道理的,因为生成的“json”内容是“entityID”参数,而不是预期的“mrequest”参数(其中包含 json:“{”attr1“: "123", "attr2":"456"}"),如环回日志所示:
loopback:connector:rest Request: {"method":"POST","uri":"http://third-party-host/plugins/aca74a80","json":"aca74a80","headers":{"authorization":"Bearer eyJhbGciOiJIUzUxMiJ9...."}} +0ms
loopback:connector:rest Error Response (status code: 400): "Request is not a JSON object" +152ms
我的问题是如何将“mrequest”内容带到“json”正文,而不是当前的“entityId”内容?
欢迎任何建议。谢谢!
解决方案
我已经解决了这个问题!
在数据源中,“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
推荐阅读
- bash - 更改从 request_uri 获得的文件名
- c++ - 如何使用 C++ 17 检查运算符!= 是否存在模板参数?
- swift - 从 appDelegate 观察 .effectiveAppearance 变化
- java - Jersey 2.x post call MessageBodyWriter not found for media type=application/xml
- c# - 我是语义模型的初学者,使用 roslyn 从 TypeSyntax 获取具体类型的 TypeSymbol 的步骤是什么?
- php - 无法让 laravel 的多态关系起作用
- xamarin - 如何在 App Center Build 中使用 .NET Core 3.0 Preview8
- c++ - C++ 触发一次事件
- python - 手动设置地理视图的纬度、经度范围
- php - 我的文件上传表单是否可以在 PWA 中使用,如果没有,我该如何实现?