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.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)