How do I make an HTTP request in Javascript?

 









In JavaScript, you can make an HTTP request using the XMLHttpRequest object or the newer fetch() function. Here's an example of how to make an HTTP GET request using XMLHttpRequest:

javascript
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/api/data');
xhr.onload = function() {
  if (xhr.status === 200) {
    console.log(xhr.responseText);
  } else {
    console.error('Error:', xhr.statusText);
  }
};
xhr.onerror = function() {
  console.error('Error:', xhr.statusText);
};
xhr.send();

In the example above, XMLHttpRequest is used to create a new request and open a GET request to the specified URL. The onload function is called when the request completes, and the response is logged to the console if the status is 200. If the status is not 200, an error message is logged. If there's an error with the request, the onerror function is called and an error message is logged.

Here's an example of how to make an HTTP GET request using fetch():

javascript
fetch('https://example.com/api/data') .then(response => { if (response.ok) { return response.text(); } else { throw new Error('Error:', response.statusText); } }) .then(data => { console.log(data); }) .catch(error => { console.error('Error:', error); });

In the example above, fetch() is used to make a GET request to the specified URL. The then() method is called on the response object, and the response is checked to see if it's ok. If it's ok, the response is returned as text. If it's not ok, an error is thrown. If there's an error with the request, the catch() method is called and an error message is logged.

Comments

Popular posts from this blog

Where is find client id in hdfc securities

Reliance Jio Infocomm IPO 2025

Tata Capital IPO Date, Price, Size, ROE, Dividend Policy and How to apply