无法使用 Promises 获取对象

Unable to fetch object using Promises

我正在使用新的 Fetch API 从 API 中检索对象。这是我的代码。

getUserYguid(){
  fetch(this.myapi, {
    credentials: "include",
    method: 'get',
    headers: {
      "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
    },
    body: null
  }).then(function(response){
    console.log(response.status)
    console.log(response.json());
    let obj = response.text();
    console.log(obj.name);
  }).catch(function(error){
    console.log('Request failed', error);
  });
}

当我调用 response.status 时,它工作正常,我可以看到状态消息为 200。 当我调用 response.json() 或 response.text() 时,我可以看到返回的完整对象。 问题是下一行代码不起作用。 当我尝试从对象中检索 属性 时,例如

console.log(obj.name);

我明白了, undefined

response.text() returns 一个承诺所以你必须再使用 then 一次

fetch(url, opts).then(function(response){
  response.text().then(function(txt){
    console.log(txt)
  })
})

而且从您的 obj.name 使用情况来看,您似乎想要 json 响应... 不是文字,所以你需要做:

fetch(url, opts).then(function(response){
  response.json().then(function(obj){
    console.log(obj.name)
  })
})

get 是默认方法,因此无需指定...并且 blob 为空,因此也不需要...