How do I make an HTTP request in Javascript?

There are several ways to make an HTTP request in JavaScript, but one of the most common and widely-used methods is to use the XMLHttpRequest object, which is built into most web browsers. Here’s an example of how to make a GET request to a website using XMLHttpRequest:

Copy codevar xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.example.com", true);
xhr.send();

You can also use the fetch() function, which is a more recent addition to JavaScript and is considered to be more modern and easier to use than XMLHttpRequest. Here’s an example of how to make a GET request to a website using fetch():

Copy codefetch("https://www.example.com")
.then(response => response.text())
.then(data => console.log(data))
.catch(error => console.error(error));

Another popular library for making HTTP requests in JavaScript is axios which is a promise based library, Here is an example:

Copy codeaxios.get('https://www.example.com')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });

You can also specify the options such as headers and query parameters for the request

Please note that the above example are for GET requests. You can make POST, PUT, DELETE request with similar syntax.

Leave a Reply