Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Lesson 6 - HTTP Requests

6.2 Handling GET Requests

The GET method is a widely-used HTTP request method for retrieving data from a server. It is typically used to fetch resources such as HTML documents, images, or data from APIs. Compared to other methods like POST, GET requests are simpler in structure and are faster for retrieving data. However, they are less secure for sending sensitive information because parameters are visible in the URL.

In JavaScript, you can perform a GET request using XMLHttpRequest() or the newer fetch() API to asynchronously retrieve data from a server.

Here's an example using XMLHttpRequest():

<!DOCTYPE html>
<html>
<head>
    <title>GET Request</title>
</head>
<body>
    <p id="responseMessage"></p>

    <script>
        const xhttp = new XMLHttpRequest();
        xhttp.onload = function() {
            document.getElementById("responseMessage").innerHTML = this.responseText;
        };

        xhttp.open("GET", "https://jsonplaceholder.typicode.com/posts");
        xhttp.send();
    </script>
</body>
</html>

In this example:

  • We create an instance of XMLHttpRequest() named xhttp.
  • We define an onload function that executes when the request completes successfully. It updates the HTML content of an element with the response received (this.responseText).
  • We use xhttp.open() to specify the HTTP method (GET) and the URL of the resource (https://jsonplaceholder.typicode.com/posts).
  • Finally, xhttp.send() initiates the request to fetch data from the specified URL.

This illustrates how JavaScript can be used to asynchronously fetch and display data from a server using a GET request.