Beginner’s Guide: Making HTTP Requests in JavaScript

In this article we going to see how to making HTTP requests in JavaScript. Here’s a step-by-step guide on how to make an HTTP request in JavaScript using the XMLHttpRequest object:
Step 1: Create a new instance of the XMLHttpRequest object:
1 |
var xhttp = new XMLHttpRequest(); |
Step 2: Specify the HTTP method and URL for the request:
1 |
xhttp.open("GET", "https://example.com/api/data", true); |
Here, we’re making a GET request to https://example.com/api/data.
Step 3: Define a callback function to handle the response:
1 2 3 4 5 |
xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { // Handle response data here } }; |
This function will be called when the request completes, and we can use it to handle the response data.
Step 4: Send the HTTP request:
1 |
xhttp.send(); |
This will send the request to the server.
Here’s an example that puts it all together:
1 2 3 4 5 6 7 8 |
var xhttp = new XMLHttpRequest(); xhttp.open("GET", "https://example.com/api/data", true); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { console.log(this.responseText); } }; xhttp.send(); |
This example sends a GET request to https://example.com/api/data, and when the response is received, it logs the response text to the console. You can modify this code to handle different types of HTTP requests and responses.
Using fetch() method, Here’s an example of each:
1 2 3 4 |
fetch("https://example.com/api/data") .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error)); |
Mraj
Creative Designer & Developer specialist by the spirit and a loving blogger by thoughts. If you have any questions let me drop an email with the article name to the following email id: [email protected]