Simple DELETE request using fetch API by making custom HTTP library
Last Updated :
17 Feb, 2021
Why fetch() API method is used?
The fetch() method is used to send the requests to the server without refreshing the page. It is an alternative to the XMLHttpRequest object. We will be taking a fake API which will contain Array as an example and from that API we will show to DELETE data by fetch API method by making custom HTTP library. The API used in this tutorial is: https://jsonplaceholder.typicode.com/users/2
Prerequisites: You should have a basic awareness of HTML, CSS, and JavaScript.
Explanation: First we need to create index.html file and paste the below code of index.html file into that. The index.html file includes
library.js and app.js files at the bottom of the body tag. Now in library.js file, first create an ES6 class DeleteHTTP and within that class, there is async fetch() function which DELETES the data from the api. There are two stages of await. First for fetch() and then for its response. Whatever response we receive, we return it to the calling function in app.js file.
Now in app.js file, first instantiate DeleteHTTP class. Then by http.delete prototype function send URL to the library.js file. Further, in this, there are two promises to be resolved. The first is for any response data and the second is for any error.
index.html
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta name = "viewport" content =
"width=device-width, initial-scale=1.0" >
< meta http-equiv = "X-UA-Compatible"
content = "ie=edge" >
< title >DELETE Request</ title >
</ head >
< body >
< h1 >
Simple DELETE request using fetch
API by making custom HTTP library
</ h1 >
< script src = "library.js" ></ script >
< script src = "app.js" ></ script >
</ body >
</ html >
|
library.js
class DeleteHTTP {
async delete (url) {
const response = await fetch(url, {
method: 'DELETE' ,
headers: {
'Content-type' : 'application/json'
}
});
const resData = 'resource deleted...' ;
return resData;
}
}
|
Filename: app.js
app.js
const http = new DeleteHTTP;
.then(data => console.log(data))
. catch (err => console.log(err));
|
Output: Open index.html file in the browser then right click-> inspect element->console. The following output you will see for DELETE request:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...