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 dummy API that will contain an array of array as an example and we will show GET and POST data by Fetch API method by making custom HTTP library.
You can use either of them.
Approach: First of all, create a “index.html” file and write the following code. This “index.html” file includes “library.js” and “app.js” files at the bottom of the “body” tag. In the “library.js” file, first create an ES6 class EasyHTTP and within that class, there is async fetch() function which fetches the data from that API URL. There are two stages of awaiting. First for fetch() method and then for its response. Whatever response the programmer receives, it is returned in the calling function of the “app.js” file.
In “app.js” file, instantiate EasyHTTP class. By GET prototype function, send URL to the “library.js” file. There are two promises to be resolved. The first is for any response data and the second is for any error.
Note: For getting GET request response you have to comment the POST request part in “library.js” file and “app.js” file. Similarly for getting POST request response, you have to comment the GET request part in the “library.js” and the “app.js” files.
index.html The implementation of the “index.html” is shown in the code.
library.js The file contains the following code.
app.js The file contains the following code.
Output: It shows the output for GET request.
Run the “index.html” file in the browser and then right click-> inspect element->console the following output, you will see for GET request.
Output: It shows the output for POST request. Run the “index.html” file in the browser, then right click-> inspect element->console the following output, you will see for POST request.