You are on page 1of 7

FETCH API

INTRODUCTION
&
EXAMPLES

in

Jaspreet Kaur
1. FETCHING DATA WITH GET REQUESTS

The simplest use case for the Fetch API is to fetch


data from a server using a GET request. Here's an
example:

fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

This code fetches data from the specified URL and


logs the response data to the console. The fetch()
method returns a promise that resolves to a
Response object. We then use the json() method
on the response object to extract the JSON data
from the response.
Jaspreet Kaur
1. SENDING DATA WITH POST REQUESTS

You can also use the Fetch API to send data to the
server using a POST request. Here's an example:
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
Jaspreet Kaur
1. HANDLING ERRORS

Network requests can fail for various reasons, such


as a server error or a network connectivity issue. To
handle errors in Fetch API, you can use the catch()
method on the returned promise. Example :-

fetch('https://jsonplaceholder.typicode.com
/posts/999')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

Jaspreet Kaur
1. USING ASYNC/AWAIT WITH FETCH API

The Fetch API also works well with the async/await


syntax, which allows for cleaner and more readable
code. Example:
async function fetchUserData(userId) {
const response = await
fetch(`https://jsonplaceholder.typicode.com/use
rs/${userId}`);
const data = await response.json();
return data;
}
fetchUserData(1)
.then(data => console.log(data))
.catch(error => console.error(error));

Jaspreet Kaur
1. ADDING HEADERS TO FETCH REQUESTS

You can also add custom headers to your Fetch


requests to provide additional information to the
server. Example:

const headers = new Headers();


headers.append('Authorization', 'Bearer token');

fetch('https://api.example.com/data', {
headers: headers
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

Jaspreet Kaur
Jaspreet Kaur

FOLLOW FOR MORE

You might also like