Reputation: 65
I am trying to create a simple AJAX request to AccuWeather but the JSON method won't convert the returned data to a JS object.
All I get is:
Status_code: "JSON_VALIDATION",
status_msg: "Syntax error. Incorrect input JSON. Please, check fields with JSON input."*
What I do wrong?
async function getWeather() {
try {
const request = await fetch(
'https://accuweatherstefan-skliarovv1.p.rapidapi.com/searchByLocationKey', {
'method': 'post',
'headers': {
'x-rapidapi-host': 'AccuWeatherstefan-skliarovV1.p.rapidapi.com',
'x-rapidapi-key': '...',
'content-type': 'application/x-www-form-urlencoded'
},
'body': {
'locationkey': 'IL',
'apiKey': 'xxxxx'
}
}
);
const data = await request.json();
return data;
} catch (error) {
alert(error);
}
}
getWeather();
getWeather('IL').then(resolved => {
console.log(resolved);
});
Upvotes: 0
Views: 63
Reputation: 1102
The problem is not with the conversion of the json response, but with sending the request. You can't send an object in body, you should send a JSON string, or in your case, create a formdata object:
const formData = new FormData();
formData.append('locationkey', 'IL');
formData.append('apiKey', 'apiKey');
and pass it as body:
const request = await fetch(
'https://accuweatherstefan-skliarovv1.p.rapidapi.com/searchByLocationKey',
{
'method': 'post',
'headers': {
'x-rapidapi-host': 'AccuWeatherstefan-skliarovV1.p.rapidapi.com',
'x-rapidapi-key': '...',
'content-type': 'application/x-www-form-urlencoded'
},
'body': formData
}
);
Upvotes: 1