Fetch API and AJAX
Fetch API
Modern replacement for XMLHttpRequest for HTTP requests.
Fetch Examples
// GET request
fetch("https://api.example.com/users")
.then(response => response.json())
.then(data => console.log(data));
// POST request
fetch("/api/users", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({name: "John"})
})
.then(response => response.json());Key Points
- Returns Promise, supports async/await.
response.ok, response.status, response.json().- Supports all HTTP methods.
- CORS considerations for cross-origin requests.