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

Lesson 6 - HTTP Requests

6.3 Handling POST Requests

POST requests are typically considered more robust and secure compared to GET requests. They are primarily used to send data from the client (such as user input from forms) to the server. Unlike GET requests, POST requests do not expose parameters in the URL, which enhances security, especially when handling sensitive information.

Here's an example demonstrating how to create a POST request using XMLHttpRequest() in JavaScript:

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

    <script>
        const xhttp = new XMLHttpRequest();
        xhttp.onload = function() {
          document.getElementById("responseMessage").innerHTML = this.responseText;
        };
        
        // Define the JSON data to be sent
        const postData = JSON.stringify({
          title: "test"
        });
        
        xhttp.open("POST", "https://jsonplaceholder.typicode.com/posts");
        xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); // Set appropriate request header
        xhttp.send(postData); // Send the POST request with the JSON data

    </script>
</body>
</html>

Explanation:

  • We create an instance of XMLHttpRequest() named xhttp.
  • We define an onload function that executes when the POST request completes. It will update the responseMessage element to add the response received from the request.
  • We use xhttp.open() to specify the HTTP method (POST) and the URL (https://jsonplaceholder.typicode.com/posts) where the data will be sent.
  • We use xhttp.send() to send the POST request, passing data (JSON.stringify({ title: 'test' }) in this example).

This example demonstrates how to send data to a server using a POST request. Adjust the data and URL according to your specific use case.