Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Status 204 shows response.ok

In my ASP.NET Core API backend, I send Status 204 when there's no data but I noticed in the front end, my fetch call is still showing response.ok.

Two questions:

  1. Is this normal behavior? I guess, it was a successful call so response could be OK, but it just threw me off.
  2. What's the best way to check for Status 204?

My current code in my React/Redux app looks like this:

export const apiCall = () => {
   return (dispatch) => fetch("/api/get", fetchOptions)
      .then((response) => {
         if(response.ok) {
            // Do something
         } else {
            // Couldn't get data!
         }
      })
};

This is my standard code block in handling fetch calls. How should I modify it to handle Status 204 scenarios?

like image 871
Sam Avatar asked Mar 07 '23 04:03

Sam


1 Answers

In addition to checking Response.ok, you can also check Response.status. Per MDN:

The status read-only property of the Response interface contains the status code of the response (e.g., 200 for a success).

Response.ok is only a check to see if the the status property is 200-299.

So, rather than just checking ok, you could do:

if (response.status === 200) {
  // Do something
} else if (response.status === 204) {
  // No data!
} else {
  // Other problem!
}
like image 77
CertainPerformance Avatar answered Mar 15 '23 15:03

CertainPerformance