我正在尝试使用访存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
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句