You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Fetch API获取数据时遇到response.status识别失败问题求助

Fixing Fetch API Response Status Recognition Issue

Hey there, let's break down what's going wrong with your Fetch API status handling code—there's a small but critical mistake that's throwing off the logic, plus a few tweaks to make things solid.

The Core Problem

Looking at your code, the first condition has a typo that breaks the entire flow:

if(response === 200) { // ❌ This compares the full Response OBJECT to a number (200)
  return data
}

You're trying to compare the complete Response object directly to the status code 200, which will never evaluate to true. Instead, you need to check the status property of the response object.

Fixed Code with Explanations

Here's the corrected version of your status function, with comments to clarify key changes:

function status(response) {
  // Parse the JSON body first—we can still access response.status afterward
  return response.json().then(data => {
    // Fix: Check response.status instead of the response object itself
    if (response.status === 200) {
      return data; // Return successful data to the next promise chain
    } else if (response.status === 400) {
      let message = data.error.error.error[0];
      return Promise.reject({ status: response.status, message });
    } else if (response.status === 401) {
      let message = data.message;
      return Promise.reject({ status: response.status, message });
    } else {
      // Catch all other non-200 status codes
      return Promise.reject({ status: response.status, data });
    }
  });
}

export default status; // Ensure proper export for reuse

Additional Tips

  1. Fetch API Behavior: Remember that Fetch only rejects promises on network failures (like no internet connection). HTTP error codes (4xx, 5xx) still resolve successfully, so your manual status checking is exactly what's needed to handle these cases.
  2. Response Object Access: Even after calling response.json(), you can still access metadata like response.status or response.headers—these properties aren't tied to consuming the response body.
  3. Error Handling: When using this status function, make sure to catch rejected promises with .catch() (for promise chains) or try/catch (if using async/await) to handle errors gracefully in your app.

内容的提问来源于stack exchange,提问作者Nicky Prabowo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:13:08