The Fetch API
The Fetch API is the modern way to load data from a server. Your page sends a request, the server replies, and your code gets the answer. Fetch returns a promise, a value that arrives later once the network finishes. That timing is the one idea you must grasp, and it is simpler than it sounds.
Start with fetch(url). It returns a promise, and you wait for the answer with .then. When the server sends JSON, an extra step parses it: response.json() turns the response body into real JavaScript values like arrays and objects. Two steps, and the data is ready to use.
Two kinds of failure exist. A network problem, like a server being down, lands in the catch block. But a 404 or 500 response still counts as a successful fetch, so you must check response.ok yourself and handle those statuses. The rule: always check response.ok, and always attach a catch.
Loading JSON
The most common use of fetch is loading JSON from an API. Chain two then calls: one to parse the response, one to use the data. Each then returns a new promise, which is why you can keep chaining.
fetch("https://example.com/api/users.json")
.then(function (res) { return res.json(); })
.then(function (data) { console.log(data); })
.catch(function () { console.log("Load failed"); });
Check response.ok
A 404 page is still a completed request, so fetch does not treat it as an error. Check response.ok, and throw inside the chain when it is false, so the catch block can show the user a friendly message.
.then(function (response) {
if (!response.ok) {
throw new Error("Server said " + response.status);
}
return response.json();
})
Syntax
fetch("data.json")
.then(function (response) {
return response.json();
})
.then(function (data) {
console.log(data);
})
.catch(function () {
console.log("Something went wrong");
});
fetch Doesn't Reject on 404
fetch only rejects on network failure — 404 is still then(). Check response.ok.
fetch(url).then(r=>{ if(!r.ok) throw new Error(r.status)})
Good to know
- fetch returns a promise; .then runs when the answer arrives.
- response.json() parses JSON into arrays and objects.
- A 404 still succeeds at the network level: check response.ok.
- Always attach a catch so failures show a message instead of silence.