使用Fetch API访问JSON [英] Using Fetch API to Access JSON

查看:86
本文介绍了使用Fetch API访问JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用fetch api来恢复一些数据,但是一旦我检索到它就无法将它映射到控制台。

I am trying to use fetch api to bring back some data, however am unable to map it to the console once I have retrieved it.

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不是函数

response.map is not a function

所以我试图解析响应,(即var data = JSON .parse)哪个不起作用,错误

so I tried to parse the response,(ie var data=JSON.parse) which did not work, with the error

SyntaxError: Unexpected token o in JSON at position 1"

有趣的是,在使用XMLHttp请求执行相同操作时,我需要解析它,所以我也会感兴趣要知道为什么这两种检索数据的方法之间存在差异。

Interestingly, when doing the same thing with a XMLHttp request, I was required to parse it, so I would also be interested to know why the difference between these two methods of retrieving the data.

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

If anyone could point me in the right direction, I would be really grateful.

推荐答案

Fetch API返回响应流。响应流不是JSON,因此尝试在其上调用 JSON.parse 将失败。要正确解析JSON响应,您需要需要使用 response.json 功能。这将返回一个承诺,以便您可以继续链。

The Fetch API returns a response stream in the promise. The response stream is not JSON, so trying to call JSON.parse on it will fail. To correctly parse a JSON response, you'll need to use the response.json function. This returns a promise so you can continue the chain.

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

这篇关于使用Fetch API访问JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆