首页 > 编程语言 >How to make an HTTP request in Javascript?

How to make an HTTP request in Javascript?

时间:2023-03-03 10:57:07浏览次数:54  
标签:object xhr make Javascript request How error data response

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 onl oad function is called when the request is successful and the response is received, and the one rror function is called if an error occurs. The response is then parsed as a JSON object using the responseType property.

标签:object,xhr,make,Javascript,request,How,error,data,response
From: https://www.cnblogs.com/NetUSA/p/17174770.html

相关文章