Learn how to make HTTP requests and handle responses using modern web APIs.
XMLHttpRequest
. It provides a cleaner and more powerful promise-based syntax for handling asynchronous communication with APIs.
Here's an example showing how to use the Fetch API to retrieve and post data:
// GET Request using Fetch API
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => console.log('GET:', data))
.catch(error => console.error('Error:', error));
// POST Request using Fetch API
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'New Post',
body: 'This is the post content',
userId: 1
})
})
.then(response => response.json())
.then(data => console.log('POST:', data))
.catch(error => console.error('Error:', error));
This code demonstrates:
fetch()
..then()
to handle Promise-based responses.response.json()
.AJAX (Asynchronous JavaScript and XML) is a technique for making asynchronous web requests to update parts of a web page without refreshing.
The modern Fetch API simplifies AJAX by using promises. It's cleaner, more powerful, and supports the full suite of HTTP methods (GET, POST, PUT, DELETE, etc.).
fetch(url, options)
initiates a request to the server.response.json()
.Q1: What does the Fetch API return?
Answer: C. Promise
Q2: Which method is used to parse a fetch response into JSON?
parseJSON()
response.text()
response.json()
JSON.parse()
Answer: C. response.json()
Q3: Which HTTP method is commonly used to submit form data?
Answer: D. POST
Q4: What is one advantage of the Fetch API over XMLHttpRequest?
Answer: C. It returns promises