【问题标题】:Unable to fetch object using Promises无法使用 Promises 获取对象
【发布时间】:2016-11-02 21:17:08
【问题描述】:

我正在使用新的 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

【问题讨论】:

    标签: javascript es6-promise


    【解决方案1】:

    response.text() 返回一个承诺,所以你必须再使用一次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 为空,因此也不需要...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多