Fetch API
Fetch API
INTRODUCTION
&
EXAMPLES
in
Jaspreet Kaur
1. FETCHING DATA WITH GET REQUESTS
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
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
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
Jaspreet Kaur
1. ADDING HEADERS TO FETCH REQUESTS
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