簡體   English   中英

在提取中處理失敗的API響應

[英]Handling failed API response in 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錯誤。 如何在提取中正確處理它,以便僅在響應成功時才設置狀態?

處理獲取響應成功/錯誤的更干凈方法是使用Response#ok只讀屬性

https://developer.mozilla.org/zh-CN/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
})

您的第一個回調函數內部的res .then函數包含一個名為status的鍵.then該鍵保存請求狀態碼。

 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)); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM