SmartCodingTips

πŸ“‘ 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?