首页 > 解决方案 > 环回休息连接器远程方法不起作用

问题描述

我使用 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”内容?

欢迎任何建议。谢谢!

标签: stronglooploopback

解决方案


我已经解决了这个问题!

在数据源中,“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

推荐阅读