res.json()) .then(data => console.log(data)); // POST request fetch("/api/users", { method: "POST", hea..."> res.json()) .then(data => console.log(data)); // POST request fetch("/api/users", { method: "POST", hea...">

YouTip LogoYouTip

AJAX Tutorial - Fetch API

Fetch API

// GET request
fetch("/api/users")
    .then(res => res.json())
    .then(data => console.log(data));

// POST request
fetch("/api/users", {
    method: "POST",
    headers: {"Content-Type": "application/json"},
    body: JSON.stringify({name: "Alice"})
});

Async/Await

async function loadUsers() {
    const res = await fetch("/api/users");
    const users = await res.json();
    console.log(users);
}

Summary

  • fetch() is the modern way to make HTTP requests
  • async/await simplifies asynchronous code
← HTML DOM Tutorial - Selection Markdown Tutorial - Syntax Gui β†’