π‘ JavaScript fetch()
Basics
The fetch()
method allows you to make HTTP requests in JavaScript. Itβs a modern alternative to XMLHttpRequest
and is Promise-based, making it easier to handle asynchronous operations.
π Syntax
fetch(url)
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error("Error:", error);
});
π Example β Fetching Users from JSONPlaceholder
fetch("https://jsonplaceholder.typicode.com/users")
.then(res => res.json())
.then(users => {
users.forEach(user => {
console.log(user.name);
});
});
π₯ GET vs POST with fetch
GET (default)
fetch("https://api.example.com/data")
POST with JSON
fetch("https://api.example.com/submit", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "John Doe",
age: 30
})
})
.then(res => res.json())
.then(data => console.log(data));
π§ͺ Handling Errors
- .catch() handles network errors
- Check response.ok for HTTP errors
fetch("https://api.example.com/data")
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
β
Tip: Use
async/await
to simplify fetch logic in modern JavaScript. Want that example next?