Horje
How to Make a HTTP Request in JavaScript?

JavaScript has great modules and methods to make HTTP requests that can be used to send or receive data from a server-side resource.

There are several approaches to making an HTTP request in JavaScript which are as follows:

Table of Content

Using fetch API

The JavaScript fetch() method is used to fetch resources from a server. It returns a Promise that resolves to the Response object representing the response to the request. The fetch method can also make HTTP requests- GET request (to get data) and POST request (to post data). Fetch also integrates advanced HTTP concepts such as CORS and other extensions to HTTP.

Example: To demonstrate making an HTTP request in JavaScript using the fetch function.

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:

Screenshot-(236)

Output

Using Ajax

Ajax is the traditional way to make an asynchronous HTTP request. Data can be sent using the HTTP POST method and received using the HTTP GET method. It uses JSONPlaceholder, a free online REST API for developers that returns random data in JSON format. To make an HTTP call in Ajax, you need to initialize a new XMLHttpRequest() method, specify the URL endpoint and HTTP method (in this case GET). Finally, we use the open() method to tie the HTTP method and URL endpoint together and call the send() method to fire off the request.

Example: To illustrates the use of XMLHttpRequest() object methods.

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>
        const xhr = new XMLHttpRequest();
        xhr
        .open("POST", "https://jsonplaceholder.typicode.com/todos");
        xhr
        .setRequestHeader("Content-Type", "application/json");
        const body = JSON
        .stringify(
        {
            userId: 1,
            title: "Demo Todo Data using XMLHttpRequest",
            completed: false,
        });
        xhr
        .onload = () => 
        {
            if (xhr.readyState == 4 && xhr.status == 201) 
            {
                console.log(JSON.parse(xhr.responseText));
            } else 
            {
                console.log(`Error: ${xhr.status}`);
            }
        };
        xhr.send(body);
    </script>
</body>

</html>

Output:

Screenshot-(238)

Output




Reffered: https://www.geeksforgeeks.org


JavaScript

Related
How to Check If It Is a Straight Line in JavaScript? How to Check If It Is a Straight Line in JavaScript?
How To Change The Browser To Fullscreen with JavaScript? How To Change The Browser To Fullscreen with JavaScript?
How to Send an HTTP POST Request in JS? How to Send an HTTP POST Request in JS?
How to Use Streaming Parsing in JavaScript? How to Use Streaming Parsing in JavaScript?
Lazy Loading Components in VueJS Lazy Loading Components in VueJS

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
15