The Fetch API is a modern JavaScript interface for making network requests. It provides a more flexible and powerful approach than XMLHttpRequest and uses Promises for asynchronous operations.
// Syntax
fetch(url, options)
Parameters:
url
: The URL of the resource to fetch.options
(Optional): An object for settings like method
, headers
, and body
.Here’s how to make a basic GET request using fetch()
to retrieve data from a public API:
// Basic Fetch Request
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Explanation: The fetch request retrieves a post, parses the response as JSON, and logs it to the console. Errors are handled with .catch()
.
The Response
object provides methods and properties to interact with the response data.
// Checking Response Properties
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
console.log('Status:', response.status);
console.log('OK:', response.ok);
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
To send data, use the POST method and include headers and a body in the options:
// POST Request
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'My Post',
body: 'This is a new post',
userId: 1
})
})
.then(response => response.json())
.then(data => console.log('Posted Data:', data))
.catch(error => console.error('Error:', error));
Explanation: This example creates a new post by sending JSON data with a POST request.
Use async/await
with Fetch API to make code cleaner and easier to read:
// Fetch with async/await
async function fetchData() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
fetchData();
Explanation: The function fetchData
makes a request using await
to wait for the response, handles errors, and logs the JSON data.
Use try...catch
blocks or .catch()
with fetch
to handle network or data errors:
// Handling Errors
fetch('https://jsonplaceholder.typicode.com/posts/invalid-endpoint')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Explanation: This example throws an error if the response is not ok and logs it to the console using .catch()
.