我想从环回应用程序中的第 3 方 REST 服务获取数据。为了从服务获取数据,我需要首先使用登录名和密码进行身份验证。我可以使用curl 测试服务:
curl -b cookies -c cookies -X POST -d '{"auth": {"username":"MyUser","password":"Secret"}}' 'http://api.awesome.service.com/'
效果很好。 Tcpdump 显示这样的请求:
Host: http://api.awesome.service.com/
User-Agent: curl/7.47.0
Accept: */*
Cookie: HBFAPI_SESSID=hbapi%3A197887%3A58a3028d12c36%3Anym2
Content-Length: 58
Content-Type: application/x-www-form-urlencoded
{"auth":{"username":"MyUser","password":"Secret"}}
所以,我首先创建了数据源:
{
"awesome_datasource": {
"name": "awesome_datasource",
"baseURL": "https://api.awesome.service.com/",
"crud": false,
"connector": "rest",
"operations": [{
"template": {
"method": "POST",
"url": "http://api.awesome.service.com/auth",
"form":{
"auth": {
"username": "{username:string}",
"password": "{password:string}"
}
},
"json": true
},
"functions":{
"login": ["username", "password"]
}
}]
}
}
我使用资源管理器测试了这一点。无论我做什么,我都无法获取格式为 json 的请求正文中的数据。无论有没有 json 选项,结果都是一样的,在 tcpdump 中是:
host: api.awesome.service.com
content-type: application/x-www-form-urlencoded
accept: application/json
content-length: 66
Connection: close
auth%5Busername%5D=MyUser&auth%5Bpassword%5D=Secret
我尝试过将参数作为“查询”、“表单”或“数据”选项传递。还检查了各种 header 内容类型选项,但到目前为止还没有运气。
模型很简单,没有参数。基本模型是“模型”(没有用户,因为我想尽可能保持简单)
我找到了这个帖子,但没有多大帮助:
https://github.com/strongloop/loopback-connector-rest/pull/12
任何建议将不胜感激。
最佳答案
那么您所要做的就是使用 json
而不是 form
:
{
"awesome_datasource": {
"name": "awesome_datasource",
"baseURL": "https://api.awesome.service.com/",
"crud": false,
"connector": "rest",
"operations": [{
"template": {
"method": "POST",
"url": "http://api.awesome.service.com/auth",
"json": {
"auth": {
"username": "{username:string}",
"password": "{password:string}"
}
}
},
"functions":{
"login": ["username", "password"]
}
}]
}
}
REST 连接器尝试模仿 request module越多越好。基本上 body
、json
、form
和 query
(请求中的qs
)与请求选项执行相同的操作,但它们也接受模板字符串。这是请求的文档,稍作修改:
query
(qs
in request) - 包含要附加到uri
的查询字符串值的对象body
- PATCH、POST 和 PUT 请求的实体主体。必须是Buffer
、String
或ReadStream
。如果json
为true
,则body
必须是 JSON 可序列化对象。form
- 当传递对象或查询字符串时,这会将body
设置为值的查询字符串表示形式,并添加Content-type: application/x-www-form-urlencoded
header 。当不传递任何选项时,将返回一个FormData
实例(并通过管道传送到请求)。请参阅上面的“表单”部分。json
- 将body
设置为值的 JSON 表示形式,并添加Content-type: application/json
header 。此外,将响应正文解析为 JSON。
关于json - Loopback:使用 REST 连接器发送带有 json 数据的请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42236438/