【问题标题】:Using curl command for react native to fetch api使用 curl 命令进行本机反应以获取 api
【发布时间】:2019-11-10 21:28:17
【问题描述】:

我正在尝试将 petfinder APi 用于我正在创建的应用程序,并遵循可在此处找到的 API 文档:https://www.petfinder.com/developers/v2/docs/#developer-resources

它给出命令:curl -d "grant_type=client_credentials&client_id={CLIENT-ID}&client_secret={CLIENT-SECRET}" https://api.petfinder.com/v2/oauth2/token

我试图将其翻译为 react native 并使用以下代码:

getAdopt1 = async() => {
fetch('https://api.petfinder.com/v2/oauth2/token', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: "grant_type=client_credentials&client_id={CLIENT-ID}&client_secret={CLIENT-SECRET}"
}),
}).then((response) => response.json())
.then((responseJson) => {
let res = JSON.stringify(responseJson)
console.log("Response: "+res)
return responseJson;
})
.catch((error) => {
console.error(error);
})
}

但是我收到以下错误:

Response: {"type":"https://httpstatus.es/400","status":400,"title":"unsupported_grant_type","detail":"The authorization grant type is not supported by the authorization server.","errors":[{"code":"unsupported_grant_type","title":"Unauthorized","message":"The authorization grant type is not supported by the authorization server. - Check that all required parameters have been provided","details":"The authorization grant type is not supported by the authorization server. - Check that all required parameters have been provided","href":"http://developer.petfinder.com/v2/errors.html#unsupported_grant_type"}],"hint":"Check that all required parameters have been provided"}

我在这里做错了什么?

【问题讨论】:

    标签: ios api react-native curl fetch


    【解决方案1】:

    您正在发送 JSON 请求,但 API 期望的是表单数据请求。

    试试这样的:

    var form = new FormData();
    
    form.append('grant_type', 'client_credentials');
    form.append('client_id', '{CLIENT-ID}');
    form.append('client_secret', '{CLIENT-SECRET}');
    
    fetch('https://api.petfinder.com/v2/oauth2/token', {
      method: 'POST',
      body: form,
    }).then(response => {
      console.log(response)
    }).catch(error => {
      console.error(error);
    })
    

    【讨论】:

    • 谢谢你,我认为这可能有效,但是有没有一种特殊的方法来打印响应,因为我得到了这个响应:响应 { "_bodyBlob": Blob { "_data": Object { "blobId ": "598BFE2F-6337-4510-86A8-6B227B9BC000", "name": "token", "offset": 0, "size": 853, "type": "application/json", }, }, "_bodyInit “:Blob {“_data”:对象{“blobId”:“598BFE2F-6337-4510-86A8-6B227B9BC000”,“名称”:“令牌”,“偏移量”:0,“大小”:853,“类型”: "应用程序/json", }, },
    • 而不是响应:{ "token_type": "Bearer", "expires_in": 3600, "access_token": "..." } 文档指出我应该得到
    • 根据响应的格式使用response.json()response.text()。如果回答正确,请采纳。
    猜你喜欢
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    • 2016-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-29
    相关资源
    最近更新 更多