Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/414.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 获取JSON.parse时出现意外字符错误_Javascript_Json_Fetch - Fatal编程技术网

Javascript 获取JSON.parse时出现意外字符错误

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调用API,它以JSON形式提供数据。当我尝试在Firefox控制台中执行下面的代码段时,第一条语句成功运行,但第二条语句出现错误,因为我想使用JSON.parse将JSON转换为对象。为什么会发生这种情况?有人能解释一下吗

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);