为什么我不能在开发者控制台中查看fetch的Response对象中的json?

问题描述 投票:0回答:2

我最近了解了JavaScript的Fetch API,我想知道为什么我不能直接从Fetch返回的Response对象中看到json数据。

例如,我有一个返回一些json的url。

fetch("https://myURL/json",
    {
        method: "GET",
        credentials: "include"
    }
)
.then(function(response) {
  if(response.ok) {
    return response.json();
  }
  throw new Error('Network response was not ok.');
}).then(function(myJson) { 
  console.log(myJson); 
})

如果我在第一个.then中放置一个断点,我可以在Chrome / Firefox的开发者控制台中查看从fetch返回的Response对象。该对象将有一些数据,但无法直接查看json。我必须调用该对象的.json()方法并将其返回以实际查看json数据。

为什么在调用.json()之前我无法在Response对象中看到json数据?当我们到达第一个.then()时,Fetch没有完成吗?

javascript fetch-api
2个回答
3
投票

根据this google developers article

fetch()请求的响应是一个Stream对象,这意味着当我们调用json()方法时,会返回一个Promise,因为流的读取将异步发生。

MDN has some info on this as well


0
投票

我不知道你在复制粘贴代码时是否犯了错误,但是你错过了URL字符串的结束引号。

除此之外,我尝试了一小段代码,它完成了它应该做的事情:

fetch("https://jsonplaceholder.typicode.com/users", {
    method: "GET",
    credentials: "include"
})
.then(function(response) {
    if (response.ok) {
        return response.json();
    }
    throw new Error('Network response was not ok.');
}).then(function(myJson) {
    console.log(myJson);
});

https://jsfiddle.net/9s9t2968/

© www.soinside.com 2019 - 2024. All rights reserved.