簡體   English   中英

使用 Fetch API 訪問 JSON

[英]Using Fetch API to Access JSON

我正在嘗試使用 fetch api 帶回一些數據,但是一旦我檢索到它就無法將其映射到控制台。

fetch('http://jsonplaceholder.typicode.com/users', { 
  method: 'GET'
}).then(function(response) {
  console.log(response)
  response.forEach(i => console.log(i.name));
}).catch(function(err) {
  console.log(`Error: ${err}` )
});

我得到的錯誤是

response.map 不是函數

所以我嘗試解析響應,(即 var data=JSON.parse)這不起作用,錯誤

SyntaxError: Unexpected token o in JSON at position 1"

有趣的是,當對 XMLHttp 請求做同樣的事情時,我需要解析它,所以我也很想知道為什么這兩種檢索數據的方法之間存在差異。

如果有人能指出我正確的方向,我將不勝感激。

Fetch API 在 Promise 中返回一個響應流 響應流不是 JSON,因此嘗試對其調用JSON.parse將失敗。 要正確解析 JSON 響應,您需要使用response.json函數。 這將返回一個承諾,因此您可以繼續該鏈。

fetch('http://jsonplaceholder.typicode.com/users', { 
  method: 'GET'
})
.then(function(response) { return response.json(); })
.then(function(json) {
  // use the json
});

理解 Promise 是使用 fetch API 的關鍵。

在您嘗試解析響應並循環遍歷它時,響應實際上只是一個承諾。 為了利用請求中實際響應的內容,您必須進行一些承諾鏈接。

fetch('http://jsonplaceholder.typicode.com/users').then(function(response) {
  // response.json() returns a promise, use the same .then syntax to work with the results
  response.json().then(function(users){
    // users is now our actual variable parsed from the json, so we can use it
    users.forEach(function(user){
      console.log(user.name)
    });
  });
}).catch(err => console.error(err));

看來您可能錯誤地訪問了 json。 您可以嘗試調用response.json()

fetch('http://jsonplaceholder.typicode.com/users', {
  method: 'GET'
}).then((response) => {
  response.json().then((jsonResponse) => {
    console.log(jsonResponse)
  })
  // assuming your json object is wrapped in an array
  response.json().then(i => i.forEach(i => console.log(i.name)))
}).catch((err) => {
  console.log(`Error: ${err}` )
});

此示例的結構與您的示例相匹配,但理想情況下,您將在第一個.then塊上返回response.json()並繼續下一個塊。 是一個類似的例子,在下一個塊上繼續。

在您的特定情況下,您可以將 Fetch API 視為“XMLHttpRequest”的 json 感知包裝器。 主要區別在於 Fetch API 更簡單、類似功能並且具有方便的方法。 David Walsh 在他的博客文章中做了一個合理的比較,我建議你看看。 普通的“XMLHttpRequest”只是將任何從服務器發回的字符串傳遞給您,它不知道它可能是 JSON,因此將其留給用戶以他們認為合適的方式解析響應。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM