How to use the Fetch API for HTTP requests
· Category: HTML & CSS
Short answer
The Fetch API provides a modern, promise-based way to make network requests. It replaces XMLHttpRequest with a cleaner interface.
Steps
- Call
fetch(url)to initiate a request. - Chain
.then(res => res.json())to parse the response. - Handle errors with
.catch()or by checkingresponse.ok.
Example
fetch('/api/data')
.then((res) => {
if (!res.ok) throw new Error('Network error');
return res.json();
})
.then((data) => console.log(data))
.catch((err) => console.error(err));
Tips
- Use
async/awaitfor cleaner syntax. - Pass an options object for POST requests with headers and body.
- Abort requests with an
AbortControllersignal.