Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptSimple GET and POST request using Fetch API method by making custom...

Simple GET and POST request using Fetch API method 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. 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.

Used API: https://jsonplaceholder.typicode.com/users

or

https://api.github.com/users .
You can use either of them.

Prerequisite: Knowledge of HTML, CSS and JavaScript.

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.

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>Get and Post request</title>
</head>
  
<body>
  
    <h1>Simple Get and POST request using fetch API
        method by making custom library</h1>
  
    <!-- Including library.js file and app.js file -->
    <script src="library.js"></script>
    <script src="app.js"></script>
</body>
  
</html>


library.js The file contains the following code.

Javascript




class EasyHTTP {
  
    // Make an HTTP GET Request 
    async get(url) {
  
        // Awaiting for fetch response
        const response = await fetch(url);
  
        // Awaiting for response.json()
        const resData = await response.json();
  
        // Returning result data
        return resData;
    }
  
    // Make an HTTP POST Request
    async post(url, data) {
  
        // Awaiting for fetch response and 
        // defining method, headers and body  
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-type': 'application/json'
            },
            body: JSON.stringify(data)
        });
  
        // Awaiting response.json()
        const resData = await response.json();
  
        // Returning result data
        return resData;
    }
}


app.js The file contains the following code.

Javascript




// Instantiating EasyHTTP
const http = new EasyHTTP;
  
// Get prototype method 
  
    // Resolving promise for response data
    .then(data => console.log(data))
  
    // Resolving promise for error
    .catch(err => console.log(err));
  
// Data for post request
const data = {
    name: 'selmon_bhoi',
    username: '_selmon',
    email: 'selmonbhoi@gmail.com'
}
  
// Post prototype method 
http.post(
    data)
  
    // resolving promise for response data
    .then(data => console.log(data))
  
    // resolving promise for error
    .catch(err => console.log(err));


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.

RELATED ARTICLES

Most Popular

Recent Comments