How to make an HTTP request in Javascript?

You can make an HTTP request in JavaScript using the built-in fetch() function or the XMLHttpRequest (XHR) object. Here are examples of how to use each of these methods:

Using the fetch() method:

fetch('https://example.com/api/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

This code sends a GET request to https://example.com/api/data, and then uses the json() method to parse the response into a JSON object.

Using the XMLHttpRequest object:

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/api/data');
xhr.responseType = 'json';
xhr.onload = () => {
  console.log(xhr.response);
};
xhr.onerror = () => {
  console.error('Error making request.');
};
xhr.send();

This code also sends a GET request to https://example.com/api/data, but uses the XMLHttpRequest object instead of the fetch() function. The onload function is called when the request is successful and the response is received, and the onerror function is called if an error occurs. The response is then parsed as a JSON object using the responseType property.

posted @ 2023-03-03 10:48  NetUSA  阅读(26)  评论(0)    收藏  举报