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 @   NetUSA  阅读(19)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示