Async & Promiseseasy
How do you use the Fetch API to perform HTTP requests?
Discuss the Fetch API's syntax and its advantages over XMLHttpRequest.
Answer
The Fetch API provides a modern way to make network requests. Basic usage includes:
- Syntax:
fetch(url, options).then(response => response.json()).then(data => console.log(data)).catch(error => console.error('Error:', error)); - Advantages:
- Promises-based, which makes chaining easier.
- Supports various request methods (GET, POST, etc.).
- Built-in handling of CORS and headers.
It simplifies asynchronous HTTP requests compared to the older XMLHttpRequest method.