Reputation: 151244
The code to show how to use fetch()
properly, even to handle 404
or 500
which is considered not an error, is to check for response.ok
:
fetch(" ")
.then(response => {
if (response.ok) return response.json();
else throw new TypeError("No fetch data");
})
.then(d => setData(d))
.catch(err => { handleError(err); });
or to check for response.status
, but the goal is to check for status code being in the range of 200 to 299, inclusive, which is what response.ok
can do.
However, if the status code is 304
, which means data has not changed, why does this case not need to be handled? I do remember in the days of jQuery, the code 304
is always checked for as well, which means it is a valid form of data. On https://code.jquery.com/jquery-3.6.0.js
isSuccess = status >= 200 && status < 300 || status === 304;
I can only see in the specs for fetch()
If response is null, then: ... If the revalidatingFlag is set and forwardResponse’s status is 304, then: ... Set response to storedResponse.
So it looks like the response is set to the cached version, but I don't see the mentioning of changing the 304
to 200
.
Why does we not need to consider the case for 304
in the case of fetch()
?
Upvotes: 0
Views: 3671
Reputation: 137171
You are doing an http-fetch request, which at step 3 enters the http-network-or-cache-fetch algorithm, which itself would enter the step 8.23 because the request is probably already in your cache.
- Set response to storedResponse.
Then the algorithm will start a new revalidateRequest to revalidate the cache in parallel, which will have its response's status set to 304, but the one response that is being returned is actually the cached one, not that 304 response.
As the note in the specs states:
This fetch is only meant to update the state of httpCache and the response will be unused until another cache access. The stale response will be used as the response to current request.
The storedResponse that is being returned was probably not a 304 response, and certainly not a null body response, so you don't need to check for it.
If the server did return a 304 response with null body, then you'd fall in the step 10 which would return a NetworkError.
Here is a glitch setup showing this, somehow.
Upvotes: 3