fetch is a built-in function that allows you to make HTTP requests to servers & retrieve or send data asynchronously.
- Returns a Promise which resolves once the response is received.
.then() and .catch() are used to handle the success & error responses.
Response object contains data, to access it you can use .json() method which again returns a promise. .text() can also be used.
- Options: You can configure request methods, headers & body.
Basic Syntax
fetch(url, options)
.then(response => {
// handle response
})
.catch(error => {
// handle error
});
Example 1: Fetching data from an API (GET request)
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json()) // convert response to JSON, returns a promise
.then(data => console.log(data)) // handle the data
.catch(error => console.error('Error:', error));
Example 2: Sending data (POST request)
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({
title: 'foo',
body: 'bar',
userID: 1,
}),
})
.then(response => response.json()) // convert response to JSON, returns a promise
.then(data => console.log(data)) // handle the data
.catch(error => console.error('Error:', error));
Example 3: Abort Controller
const controller = new AbortController()
fetch('https://jsonplaceholder.typicode.com/posts/1',
{
signal: controller.signal,
})
.then(response => response.json()) // convert response to JSON, returns a promise
.then(data => console.log(data)) // handle the data
.catch(error => console.error('Error:', error));
// to cancel the request
controller.abort();
Resources