簡體   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