JavaScript HTTP 请求:使用 XMLHttpRequest、Fetch API 和 Axios
要使用 JavaScript 发出 HTTP 请求,您可以使用内置的浏览器 API 或第三方库,如 Axios 或 Fetch。以下是使用原生 JavaScript 进行 HTTP 请求的示例:
使用内置的 XMLHttpRequest 对象:
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
console.log(response);
}
};
xhr.send();
使用 Fetch API:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));
使用 Axios 库(需要先安装):
axios.get('https://api.example.com/data')
.then(response => console.log(response.data))
.catch(error => console.log(error));
请注意,这只是 HTTP 请求的基本示例。根据您的需求,您可能需要添加其他选项或参数来处理请求。
原文地址: https://www.cveoy.top/t/topic/bXDq 著作权归作者所有。请勿转载和采集!