Loading lessons...
The Fetch API
The Fetch API
The Fetch API lets you request data from servers. It is the modern way to do network requests.
A basic fetch
fetch("https://api.example.com/data")
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log("Request failed");
});
With async/await
async function loadData() {
try {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
console.log(data);
} catch (err) {
console.log("Request failed");
}
}
The response.json() step
fetch gives you a response object. To get the JSON data, call response.json(), which itself returns a promise.
Sending data with POST
fetch("https://api.example.com/data", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Ada" })
});
Why fetch?
- Built into the browser, no library needed.
- Uses promises (or async/await).
- Replaces the older XMLHttpRequest (AJAX).
TL;DR
- fetch(URL) starts a request and returns a promise.
- response.json() parses the reply into data.
- Use .then chains or async/await.
- fetch works with GET, POST, and more.