Fetch API Cheatsheet
Fetch API Cheatsheet
There are AJAX and XMLHttpRequest also for making API request but they are
little complex in compare to Fetch method.
Now for handling promise, we use then method. First of all, we have to convert
the response(which API send) into json format. So for that we use res.json()
Now this then method again return a promise. So we use another then method
to handle it and we get the data as parameter.
fetch("https://jsonplaceholder.typicode.com/users")
.then((res) => res.json())
.then((data) => console.log(data));
So for making POST request we have to pass POST api url as first argument.
But we have to pass one more argument which is configuration object.
This object has few properties. Like method for specify API method, body for
sending data with that request but for some API we have to convert our data in
const data = {
title: "This is title",
body: "This is post body",
userId: 2,
};
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-type": "application/json",
},
})
.then((res) => res.json())
.then((data) => console.log(data));
Now if you want to make PUT or DELETE request, then you have to only change
the method type in configuration object.
getUsers();
If you don’t know promise and async-await, don’t worry I created tutorial on
Asynchronous JavaScript and in that I explain it in very detailed way.
Thank you so much for accessing this cheatsheet. If you like this then you can watch
my more tutorial on My YouTube channel ~ Code Bless You 💟