What is fetch():
- fetch() is a built-in function used to make network/HTTP requests.
- It returns a Promise.
- The fetch() function returns a Promise which is fulfilled with a Response object representing the server's response.
- You can then check the request status and extract the body of the response in various formats, including text and JSON.
HTTP Methods :
GET - get data
POST - create data
PUT - update data
DELETE - delete data
Syntax : fetch(url, options)
url → API endpoint
options → method, headers, body, etc.
fetch(url) - Sends request,Returns a Promise.
.then(response => ...) - response contains, status (200, 404…),headers,body -not readable yet.
response.json() - Converts body into JavaScript object,also returns a Promise.
.then(data => console.log(data)) - get data.
Basic get request :
fetch("https://jsonplaceholder.typicode.com/posts")
.then ((response)=> response.json())
.then ((data)=> console.log(data))
.catch((err)=> console.log(err));
fetch("https://jsonplaceholder.typicode.com/posts")
.then ((response)=> response.text())
.then ((data)=> console.log(data))
.catch((err)=> console.log(err));
Handling Error :
fetch("https://jsonplaceholder.typicode.com/post")
.then(res => {
if (!res.ok) {
throw new Error("HTTP Error: " + res.status);
}
return res.json();
})
.then(data => console.log(data))
.catch(err => console.log(err));
POST Request Example :
fetch("https://jsonplaceholder.typicode.com/posts",{
method : "post",
headers : {
"Content-Type": "application/json"
},
body : JSON.stringify({
title : "JS",
body : "Learning ftech"
})
})
.then(res => {
if (!res.ok) {
throw new Error("HTTP Error: " + res.status);
}
return res.json();
})
.then(data => console.log(data))
.catch(err => console.log(err));
Output : {title: 'JS', body: 'Learning ftech', id: 101}
What happenes here is,
fetch(...) - Sends POST request, Returns a Response object, POST request usually returns newly created/updated resource. Here it returns
res looks like below image, It does not contain the data directly.
res.json() - Reads the response body, Converts JSON to JavaScript object, Returns a Promise.
data - Final output from API
PUT Request Example :
fetch("https://jsonplaceholder.typicode.com/posts/1",{
method : "PUT",
headers : {
"Content-Type": "application/json"
},
body : JSON.stringify({
title : "JS",
body : "Learning JS",
id : 101
})
})
.then(res => {
if (!res.ok) {
throw new Error("HTTP Error: " + res.status);
}
return res.json();
})
.then(data => console.log(data))
.catch(err => console.log(err));
DELETE Request Example :
fetch("https://jsonplaceholder.typicode.com/posts/1",{
method : "DELETE",
})
.then(res => {
if (!res.ok) {
throw new Error("HTTP Error: " + res.status);
}
return res.json();
})
.then(data => console.log(data))
.catch(err => console.log(err));

Top comments (0)