使用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
- 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.
- Response Object Access: Even after calling
response.json(), you can still access metadata likeresponse.statusorresponse.headers—these properties aren't tied to consuming the response body. - Error Handling: When using this
statusfunction, make sure to catch rejected promises with.catch()(for promise chains) ortry/catch(if using async/await) to handle errors gracefully in your app.
内容的提问来源于stack exchange,提问作者Nicky Prabowo
相关产品推荐
相关产品推荐

