How to use Fetch In HTTP

In this approach, the body holds the data to be sent to the server which is added to the JSON Placeholder todos API. Also, the headers hold the type of content you want to send to the server, which in this case is JSON data.

Example: To demonstrate sending an HTTP POST request using the fetch method in JavaScript.

HTML
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0" />
  </head>
  <body>
    <script>
      fetch("https://jsonplaceholder.typicode.com/todos",
    {
        method: "POST",
        body: JSON
        .stringify
        ({
          userId: 1,
          title: "Demo Todo Data",
          completed: false,
        }),
        headers: {
          "Content-type": "application/json",
        },
      })
        .then((response) => response.json())
        .then((json) => console.log(json));
    </script>
  </body>
</html>

Output:

Sending HTTP POST request in JavaScript using the Fetch method in JavaScript.

How to Send an HTTP POST Request in JS?

We are going to send an API HTTP POST request in JavaScript using fetch API. The FetchAPI is a built-in method that takes in one compulsory parameter: the endpoint (API URL). While the other parameters may not be necessary when making a GET request, they are very useful for the POST HTTP request.

The second parameter is used to define the body (data to be sent) and type of request to be sent, while the third parameter is the header that specifies the type of data you will send, for example, JSON. The Fetch API is based on JavaScript promises, so you need to use the .then method to access the promise or response returned. There are several methods to send an HTTP POST request in JavaScript which are as follows:

Table of Content

  • Using Fetch
  • Using Ajax( XMLHttpRequest)

Similar Reads

Using Fetch

In this approach, the body holds the data to be sent to the server which is added to the JSON Placeholder todos API. Also, the headers hold the type of content you want to send to the server, which in this case is JSON data....

Using Ajax( XMLHttpRequest)

Ajax XMLHttpRequest is a in-built function and has existed much longer than the Fetch API. This means that almost all modern browsers have a built-in XMLHttpRequest object to request data from a server....