Javascript 获取JSON.parse时出现意外字符错误
我正在使用fetch调用API,它以JSON形式提供数据。当我尝试在Firefox控制台中执行下面的代码段时,第一条语句成功运行,但第二条语句出现错误,因为我想使用JSON.parse将JSON转换为对象。为什么会发生这种情况?有人能解释一下吗Javascript 获取JSON.parse时出现意外字符错误,javascript,json,fetch,Javascript,Json,Fetch,我正在使用fetch调用API,它以JSON形式提供数据。当我尝试在Firefox控制台中执行下面的代码段时,第一条语句成功运行,但第二条语句出现错误,因为我想使用JSON.parse将JSON转换为对象。为什么会发生这种情况?有人能解释一下吗 fetch('https://www.metaweather.com/api/location/44418/').then((result)=>console.log(result)); fetch('https://www.metaweathe
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));});
控制台结果:
我试着去拿https://www.metaweather.com/api/location/44418/'.thenresult=>{return result.json}.thenconsole.log;&它起作用了
请注意,我正在使用cors加载项绕过同源策略。fetch返回的承诺将解析为响应对象,而不是包含响应主体的字符串
你可以在截图中看到这一点
使用请求对象的json方法获取响应主体并将其解析为json
const response = await fetch('https://www.metaweather.com/api/location/44418/')
console.log(response);
const data = await response.json();
console.log(data);