Loopback.io休息连接器 - json帖子不工作

时间:2015-02-16 15:07:00

标签: node.js rest express loopbackjs

我正在尝试使用loopback-rest-connector代理休息服务。远程休息服务方法是POST,需要一个参数。当我使用查询字符串调用loopback端点时,一切正常。当我使用body json对象调用服务时,我得到的错误是所需的变量未定义但参数位于对象ctx.req.body中。 Loopback看不到它们。我试图添加bodysarser中间件,但它也没有用。

Datasource.js

{
      "db": {
        "name": "db",
        "connector": "memory",
        "file": "db.json"
      },

      "rest": {
        "name": "rest",
        "connector": "rest"
      },
      "geoRest": {
            "connector": "rest",
            "debug": "true",
            "operations": [{

                "template": {
                    "method": "POST",
                    "url": "https://url/endpoint",
                    "headers": {
                        "accept": "application/json",
                        "content-type": "application/json",
                        "Authorization": "sdfsdf"
                    },
                    "body": {
                        "address": "{^address:string}",
                        "country": "{country:string}"
                    }
                },
                "functions": {
                    "geocode": ["address", "country"]
                }
            }]
        }
    }

模型定义

{
  "name": "geoRest",
  "plural": "geoRests",
  "base": "Model",
  "strict": true,
  "idInjection": false,
  "properties": {},
  "validations": [],
  "relations": {},
  "acls": [],
  "methods": []
}

模型配置

"geoRest": {
    "dataSource": "geoRest",
    "public": true
  }

1 个答案:

答案 0 :(得分:2)

尝试使用form代替body。修改后的template部分应如下所示:

"template": {
    "method": "POST",
    "url": "https://url/endpoint",
    "headers": {
        "accept": "application/json",
        "content-type": "application/json",
        "Authorization": "sdfsdf"
    },
    "form": {
        "address": "{^address:string}",
        "country": "{country:string}"
    }
},

使用form将发送您的参数,就像使用POST方法提交表单一样,因此作为请求正文的一部分。

使用bodyreq时,会将其附加到request-url,即基本上以查询参数的形式发送。