How do I make an HTTP request in Javascript?

There are several ways to make an HTTP request in JavaScript, including:

  1. Using the XMLHttpRequest object (also known as the "XHR object") which is built into most modern browsers. This method allows you to send and receive data asynchronously, without the need for a full page refresh.

  2. Using the fetch() method, which is a more modern and simpler way to make requests. It also allows you to send and receive data asynchronously and returns a promise that resolves to the response.

  3. Using a library such as axios or superagent which provide a more powerful and flexible API for making requests.

Here's an example of how to use XMLHttpRequest to make a GET request to a specified URL:

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

And here's an example of how to use fetch() to make a GET request to a specified URL:

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

Note: Keep in mind that CORS(Cross-Origin Resource Sharing) policy, if your request is not from the same origin it will be blocked by the browser.


 

Post a Comment

0 Comments