How to make simple PUT request using fetch API by making custom HTTP library ?
The fetch() method is used to send the requests to the server without refreshing the page. It is an alternative to the XMLHttpRequest object. It will be taking a fake API that will contain Array as an example and from that API we will show to PUT/Update 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. This 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 EasyHTTP and within that class there is async fetch() function that puts the data to the api url. 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 EasyHTTP class. Then by put 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 PUT request.