[JavaScript] Fetch API - GET, POST, PUT, DELETE to Send a Request to the Server. Explained with Examples.

·

3 min read

[JavaScript] Fetch API - GET, POST, PUT, DELETE to Send a Request to the Server. Explained with Examples.

Introduction

This article will be exploring four methods that you need, in order to communicate with the server.

  1. GET - to retrieve the data.

  2. POST - to send the data

  3. PUT - to replace the data

  4. DELETE - to delete the data

At the end of this article, there will be a demonstration of implementation.

Fetch API is different from XMLHttpRequest. In Fetch API, you do not need to use Promise Object to promise the response.

Check out this article: [JavaScript] Understanding XMLHttpRequest if you want to compare the difference between XMLHttpRequest and Fetch API.


GET

function getPostData() {
    fetch("http://localhost:3000/posts") // url
    .then((response) => response.json()) // converts response to json type.
    .then((json) => console.log(json)) // prints out the response you've got
}

Do you realize how much the code is simplified compared to the XMLHttpRequest?

With this function, you will be able to retrieve the data from your server.

Just make sure that the URL is correct unless you might get an error:

Uncaught (in promise) typeerror: failed to fetch


POST

In XMLHttpRequest, it was necessary to use open(), sendRequestHeader() and send() to specify things.

In Fetch API, things are more simplified.

function postData() {
    const data = { title: "HTML", author: "John Doe" };
    const headers = {"context-type": "application/json;charset=UTF-8"};
    fetch("http://localhost:3000/posts", {
    // method instead of open()
    method: "POST",
    // body instead of send()
    body: JSON.stringify(data),
    // headers instead of sendRequestHeader()
    headers: headers
    }).then((response) => response.json())
    .then((json) => console.log(json));
}

In practice, I will put the data and headers variable outside the function, but I will put them in the function for demonstration.


PUT

function putData() {
    const headers = {"context-type": "application/json;charset=UTF-8"};
    const data = { title: "Fetch API", author: "John Doe" };
    // make sure to specify what you want to replace. 
    // in the back of my url, I specified that I want to replace id = 2
    fetch("http://localhost:3000/posts/2", {
    method: "PUT",
    body: JSON.stringify(data),
    headers: headers
    }).then((response) => response.json)
    .then((json) => console.log(json));
}

DELETE

function deleteData() {
    // make sure to specify what you want to delete. 
    // in the back of my url, I specified that I want to delete id = 2
    fetch("http://localhost:3000/posts/2", {
        // you do not need to specify body and header.
        method: "DELETE"
    }).then((response) => response.json)
    .then((json) => console.log(json));
}

Implementation

Now, let's see if it works.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button onclick="getPostData();">GET</button>
    <button onclick="postData();">POST</button>
    <button onclick="putData();">PUT</button>
    <button onclick="deleteData();">DELETE</button>
  </body>
</html>

GET to check the original data

POST to send the data

PUT to replace the data with id: 2

DELETE to delete the data with id: 2

Did you find this article valuable?

Support Jay's Dev Blog by becoming a sponsor. Any amount is appreciated!