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
Explanation: First of all 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 file at the bottom of the body tag. Now in library.js file, first of all 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 of all instantiate DeleteHTTP class. Then by http.delete prototype function send url to the to the library.js file. Further in this there are two promises to be resolved. First is for any response data and the second is for any error.
Output: Open index.html file in the browser then right click-> inspect element->console. The following output you will see for DELETE request:
- Simple GET and POST request using Fetch API method by making custom HTTP library
- How to make simple PUT request using fetch API by making custom HTTP library ?
- DELETE request using XMLHttpRequest by making Custom HTTP library
- Get request using AJAX by making Custom HTTP library
- POST request using AJAX by making Custom HTTP library
- How to make PUT request using XMLHttpRequest by making Custom HTTP library ?
- Simple POST request using the fetch API
- HTTP Request vs HapiJS Request in Node.js
- Difference between Fetch and Axios.js for making http requests
- Get and Post method using Fetch API
- AngularJS | fetch data from API using HttpClient
- HTTP headers | Access-Control-Request-Headers
- HTTP headers | Access-Control-Request-Method
- How HTTP POST request work in node.js ?
- Fetch API
- D3.js d3-Fetch API
- Making a simple PWA under 5 minutes
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.