How do I make an HTTP request in Javascript?

To make an HTTP request in JavaScript, you can use the XMLHttpRequest object or the newer fetch() API. Here is an example of how to use XMLHttpRequest to make a GET request to fetch a resource from a server:

// Create a new XMLHttpRequest object const xhr = new XMLHttpRequest();
// Set the HTTP method to GET, the URL to fetch, and specify that the request is asynchronous
xhr.open("GET", "https://www.example.com/resource", true);
// Set a function to be called when the request is complete
xhr.onload = function() {
// Check the status code to make sure the request was successful
if (this.status == 200) {
// If successful, do something with the response data var data =
JSON.parse(this.responseText);
// ...
} };
// Send the request
xhr.send();

Here is an example of how to use the fetch() API to make a GET request:

fetch("https://www.example.com/resource")
.then(response => response.json())
.then(data => {
// Do something with the response data // ...
});

Both XMLHttpRequest and fetch() allow you to specify additional options and customize the request, such as by setting request headers or providing a request body for POST requests. Consult the documentation for more information.

DCT Academy
Full Stack Development Training Institute

Launch your GraphyLaunch your Graphy
100K+ creators trust Graphy to teach online
𝕏
Best MERN Full Stack Development Course | Bangalore | Offline | Online | 100% Placements | Training Institute | Front End Course | React JS Training | Online Course India 2024 Privacy policy Terms of use Contact us Refund policy