How to use the GET and POST method of Fetch API in JavaScript

This post will give an introductory explanation about using this method to get data from servers or post data to servers.

What is the Fetch API?

Fetch API is a web standard created predominantly for web browers which is used to send HTTP requests to the server without refreshing the page like AJAX in jQuery, providing an effecient alternative to the older XMLHttpRequest object. This API is performed via the fetch() method that it uses Promises, which allow for handling asynchronous operations better compared to callbacks.

Introduction of the demonstration

The index page has two buttons: one button for clicking to load users and the other for clicking to add a new user. Apart from the buttons, the page also has a table placeholder where the users are displayed.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Using Fetch API</title>
</head>
<body>
  <h1>Using Fetch API to send GET and POST request</h1>
  <h2>Using GET to fetch the users</h2>
  <input type="button" id="btnFetchUsers" value="Fetch Users" onclick="fetchUsers()">
  <table id="users"></table>
  <h2>Using POST to add a new user</h2>
  <input type="button" id="btnAddUser" value="Add User" onclick="addUser()">
<script>

</script>
<script src="main.js"></script>
</body>
</html>

When loading this HTML page, you’ll see the result look like the screenshot below.The functions tied to these buttons are explained in the next sections.

Send a GET request

Simply call fetch() with the endpoint URL as one of the required arguments

fetch('https://jsonplaceholder.typicode.com/users')

The command above will drag and return you a list of users with the fields such as id, name, username, email, address, phone, website and company. The full version of GET request looks like the snippet below.

//  main.js
 
//  GET request using fetch()
fetch("https://jsonplaceholder.typicode.com/users")
  
    // Converting received data to JSON
    .then(response => response.json())
    .then(json => {
 
        // Create a variable to store HTML
        let li = `<tr><th>Name</th><th>Email</th></tr>`;
      
        // Loop through each data and add a table row
        json.forEach(user => {
            li += `<tr>
                <td>${user.name} </td>
                <td>${user.email}</td>         
            </tr>`;
        });
 
    // Display result
    document.getElementById("users").innerHTML = li;
});

Whening opening this HTML page, you’ll see the result as follows.

Send a POST request

To a POST request, we need to pass the body argument to the fetch() method. The body is a JSON-typed object, for example, below is a valid data body for the fetch method.

{
   title: "foo",
   body: "bar",
   userId: 1
}

The complete POST request looks like

fetch("https://jsonplaceholder.typicode.com/posts", {

        // Adding method type
        method: "POST",

        // Adding body or contents to send
        body: JSON.stringify({
            title: "foo",
            body: "bar",
            userId: 1
        }),

        // Adding headers to the request
        headers: {
            "Content-type": "application/json; charset=UTF-8"
        }
    })

        // Converting to JSON
        .then(response => response.json())

        // Displaying results to console
        .then(json => console.log(json));

When clicking the Fetch Users button, you’ll see the result looks like the screenshot below.

The POST requests shows the status 204 indicating CREATED. Both requests show fetch in the type column.

Nguyen Vu Ngoc Tung

I love making new professional acquaintances. Don't hesitate to contact me via nguyenvungoctung@gmail.com if you want to talk about information technology, education, and research on complex networks analysis (i.e., metabolic networks analysis), data analysis, and applications of graph theory. Specialties: researching and proposing innovative business approaches to organizations, evaluating and consulting about usability engineering, training and employee development, web technologies, software architecture.

https://www.itersdesktop.com/author/nvntung/

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.