我正在尝试将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"}
我在这里做什么错了?
答案 0 :(得分:1)
您正在发送JSON请求,但API期望的是Form-Data请求。
尝试如下所示:
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);
})