使用 Fetch API 访问 JSON

IT技术 javascript json
2021-01-28 11:24:36

我正在尝试使用 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 请求做同样的事情时,我需要解析它,所以我也很想知道为什么这两种检索数据的方法之间的区别。

如果有人能指出我正确的方向,我将不胜感激。

3个回答

Fetch API在Promise中返回一个响应流响应流不是 JSON,因此尝试调用JSON.parse它会失败。要正确解析 JSON 响应,您需要使用response.json函数。这将返回一个Promise,以便您可以继续链。

fetch('http://jsonplaceholder.typicode.com/users', { 
  method: 'GET'
})
.then(function(response) { return response.json(); })
.then(function(json) {
  // use the json
});
我知道这个答案是在 2016 年给出的……但现在是 2020 年,MDN 文档仍然说 .json() 是一种实验性且支持不足的方法。使用它成为具有广泛兼容性的噩梦(尤其是在移动市场)。
2021-03-15 11:24:36
@Phil 不错,是时候了!感谢您提醒并更新此答案。
2021-03-23 11:24:36
@IncredibleHat 现在没有警告。如需参考,请参阅caniuse.com/mdn-api_response_json
2021-03-31 11:24:36

理解 Promise 是使用 fetch API 的关键。

当您尝试解析您的响应并遍历它时,响应实际上只是一个Promise。为了利用来自请求实际响应的内容,您必须进行一些Promise链接。

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));
forEach 不是异步的。传下去。
2021-03-14 11:24:36
非常感谢,很好的解释!
2021-04-11 11:24:36

看来您可能错误地访问了 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}` )
});

此示例的结构与您的示例相匹配,但理想情况下,您将返回response.json()第一个.then块并继续下一个块。是在下一个块上进行的类似示例。

在您的特定情况下,您可以将 Fetch API 视为“XMLHttpRequest”的 json 感知包装器。主要区别在于 Fetch API 更简单、类似函数,并且具有方便的方法。David Walsh 在他的博客文章中做了一个合理的比较,我建议你看一看。普通的“XMLHttpRequest”只是向您传递从服务器发回的任何字符串,它不知道它可能是 JSON,因此让用户以他们认为合适的任何方式解析响应。

对于那个很抱歉。已编辑。@ShamSUP 感谢您指出!
2021-03-31 11:24:36
response.json()返回一个Promise,所以你不能只对它调用 forEach。更多类似的东西response.json().then(function(users){users.forEach(function(user){console.log(user.name)})
2021-04-03 11:24:36