我正在尝试向 AccuWeather 创建一个简单的 AJAX 请求,但 JSON 方法不会将返回的数据转换为 JS 对象。
我得到的只是:
状态代码:“JSON_VALIDATION”,
status_msg: "语法错误。输入的 JSON 不正确。请检查包含 JSON 输入的字段。"*
我做错了什么?
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);
});
问题不在于json响应的转换,而在于发送请求。您不能在正文中发送对象,您应该发送 JSON 字符串,或者根据您的情况,创建一个 formdata 对象:
const formData = new FormData();
formData.append('locationkey', 'IL');
formData.append('apiKey', 'apiKey');
并将其作为正文传递:
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
}
);