JavaScript HTTP 请求:XMLHttpRequest 和 Fetch API
使用 JavaScript 发出 HTTP 请求可以使用内置的 XMLHttpRequest 对象或者使用现代的 fetch 函数。下面是两种方式的示例代码:
使用 XMLHttpRequest 对象:
function makeHttpRequest(url, method) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response);
} else {
reject(new Error(xhr.statusText));
}
};
xhr.onerror = function() {
reject(new Error('Network Error'));
};
xhr.send();
});
}
// 例子使用GET请求
makeHttpRequest('https://api.example.com/data', 'GET')
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.error(error);
});
使用 fetch 函数:
function makeHttpRequest(url, method) {
return fetch(url, { method: method })
.then(function(response) {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json();
})
.then(function(data) {
return data;
})
.catch(function(error) {
console.error(error);
});
}
// 例子使用GET请求
makeHttpRequest('https://api.example.com/data', 'GET')
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.error(error);
});
这些代码片段可以通过JavaScript在浏览器或Node.js环境中运行,用于发出HTTP请求并处理响应。
原文地址: https://www.cveoy.top/t/topic/NXD 著作权归作者所有。请勿转载和采集!