【问题标题】:Handling failed API response in fetch在 fetch 中处理失败的 API 响应
【发布时间】:2017-11-11 00:33:25
【问题描述】:

在我的应用程序中,我有一个简单的 fetch 用于检索通过身份验证令牌发送到 API 的用户列表

fetch("/users", {
  method: "POST",
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    token: this.props.getUser().token
  })
})
  .then(res => res.json())
  .then(users => this.setState({ users }))
  .catch(err => {
     console.error(err);
   });

但是,如果令牌过期,API 可能会返回 401 错误。 如何在 fetch 中正确处理,以便仅在响应成功时设置状态?

【问题讨论】:

  • 你会在.then(res => res.json())中检查返回的状态,而不是盲目地返回res.json()
  • res 在第一个 .then 的回调中应该有一个名为 status 的键。这就是你要找的。​​span>

标签: javascript node.js reactjs promise


【解决方案1】:

处理获取响应的成功/错误的更简洁的方法是使用Response#ok readonly 属性

https://developer.mozilla.org/en-US/docs/Web/API/Response/ok

fetch('/users').then((response) => {
  if (response.ok) {
    return response.json();
  }
  throw response;
}).then((users) => {
  this.setState({
    users
  });
}).catch((error) => {
  // whatever
})

【讨论】:

    【解决方案2】:

    res 在您的第一个 .then 函数中的回调函数内包含一个名为 status 的键,其中包含请求状态代码。

    const url = 'https://api.myjson.com/bins/s41un';
    
    fetch(url).then((res) => {
      console.log('status code:', res.status); // heres the response status code
      
      if (res.status === 200) {
        return res.json();   // request successful (status code 200)
      }
      
      return Promise.reject(new Error('token expired!')); // status code different than 200
      
    }).then((response) => console.log(response)); 

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-16
      • 2016-07-13
      • 2017-02-09
      • 2017-03-07
      • 2015-05-21
      • 1970-01-01
      • 2021-08-07
      • 2021-05-07
      相关资源
      最近更新 更多