CodePark/ questions / Fetch, CORS & HTTP versions
START PRACTICINGPRACTICE
Frontend question · Browser & web performance › Fetch, CORS & HTTP versions

The server responds with 404. What does this log?

fetch("/api/missing")
  .then((res) => console.log("then", res.ok, res.status))
  .catch(() => console.log("catch"));
then false 404

fetch only rejects on network failures, such as being offline, DNS errors or CORS blocking. An HTTP error status like 404 still resolves, with res.ok set to false. So the code logs then false 404, and you must check res.ok yourself.

catch is the tempting wrong answer. Many people expect a 404 to reject, but it doesn't. "then false 404 followed by catch" is wrong for the same reason. then true 404 is wrong, because res.ok is only true for status codes 200 to 299.