Использование команды curl для реакции нативного на получение api - PullRequest
0 голосов
/ 11 ноября 2019

Я пытаюсь использовать 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

Я пытаюсь перевести это для реагирования на натив и использовал следующий код:

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"}

Что я здесь не так делаю?

1 Ответ

1 голос
/ 11 ноября 2019

Вы отправляете запрос 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);
})
...