You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

ASP.NET Core API返回Status 204时fetch仍显示response.ok的问题与处理

Answers to Your ASP.NET Core API & Fetch Questions

1. Is this normal behavior?

Absolutely, this is completely normal! The response.ok property in fetch returns true for any HTTP status code between 200 and 299, which includes the 204 "No Content" status.

204 is a successful status code—it means your request was processed correctly by the server, there just isn't any data to send back in the response body. That's why response.ok is still true even when there's no data. It's confusing at first, but it aligns with HTTP standards where all 2xx codes indicate a successful request.

2. Best way to check for Status 204

The most straightforward way is to explicitly check the response.status property. Since 204 falls under the "ok" range, you'll need to handle it inside the response.ok block before trying to parse the response body (because a 204 response has no body, calling methods like response.json() will throw an error).

Modified Code Example

Here's how to adjust your React/Redux apiCall function to handle the 204 scenario properly:

export const apiCall = () => {
  return (dispatch) => fetch("/api/get", fetchOptions)
    .then((response) => {
      if (response.ok) {
        // Check for 204 No Content first to avoid parsing errors
        if (response.status === 204) {
          // Dispatch an action to handle empty data state
          dispatch({ type: 'FETCH_NO_DATA_AVAILABLE' });
          return Promise.resolve(null); // Resolve cleanly without parsing
        }
        
        // For other successful statuses (like 200), parse the response body
        return response.json().then(data => {
          // Process data and dispatch success action
          dispatch({ type: 'FETCH_SUCCESS', payload: data });
        });
      } else {
        // Handle error statuses (4xx, 5xx)
        dispatch({ type: 'FETCH_FAILURE', payload: 'Couldn\'t get data!' });
      }
    })
    .catch((error) => {
      // Catch network errors or unexpected parsing issues
      dispatch({ type: 'FETCH_FAILURE', payload: error.message });
    });
};

Key Notes:

  • Check for 204 first: This prevents trying to parse an empty response body, which would trigger an unhandled error.
  • Distinct action types: Use specific actions like FETCH_NO_DATA_AVAILABLE so your reducers can update the UI to reflect the empty state clearly.
  • Add a catch block: This covers network failures or any unexpected issues that might occur during the fetch process.

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

火山引擎 最新活动