繁体   English   中英

获取 JSON.parse 意外字符错误

[英]Getting JSON.parse unexpected character error

I am calling API with fetch() which delivers data in JSON form.When i try to execute below code snippet in Firefox console,first statement runs succesfully but second statement get an error as i want to convert json to object using JSON.parse( )。为什么会这样?谁能解释一下。

fetch('https://www.metaweather.com/api/location/44418/').then((result)=>console.log(result));

fetch('https://www.metaweather.com/api/location/44418/').then((result)=>{console.log(JSON.parse(result.body));});

控制台结果:

在此处输入图像描述

我试过fetch('https://www.metaweather.com/api/location/44418/').then(result => {return result.json()}).then(console.log); & 有用。

请注意,我正在使用 cors 插件来绕过相同的来源策略。

fetch返回的 promise 解析为响应 object,而不是包含响应正文的字符串。

你可以在你的截图中看到!

使用 Request 对象的json()方法获取响应的正文并将其解析为 JSON。

const response = await fetch('https://www.metaweather.com/api/location/44418/')
console.log(response);
const data = await response.json();
console.log(data);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM