JavaScript HTTP 请求:XMLHttpRequest 和 Fetch 函数
使用 JavaScript 发出 HTTP 请求可以通过内置的 XMLHttpRequest 对象或者使用现代化的 fetch 函数来实现。在 GPT-3.5-Turbo 版中,以下是使用这两种方法之一发送 HTTP 请求的示例代码:
使用 XMLHttpRequest 对象:
function sendHttpRequest(url, method, headers, data, callback) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
// 设置请求头
for (var key in headers) {
xhr.setRequestHeader(key, headers[key]);
}
// 处理响应
xhr.onload = function() {
if (xhr.status === 200) {
callback(null, xhr.responseText);
} else {
callback('Error: ' + xhr.status);
}
};
// 发送请求
xhr.send(data);
}
使用 fetch 函数:
function sendHttpRequest(url, method, headers, data, callback) {
fetch(url, {
method: method,
headers: headers,
body: data
})
.then(function(response) {
if (!response.ok) {
throw new Error('Error: ' + response.status);
}
return response.text();
})
.then(function(data) {
callback(null, data);
})
.catch(function(error) {
callback(error.message);
});
}
你可以使用上述函数来发送 HTTP 请求。你需要提供 URL,HTTP 方法(例如,GET、POST 等),请求头,请求体(对于需要的请求类型),以及一个回调函数来处理响应。
原文地址: https://www.cveoy.top/t/topic/JZr 著作权归作者所有。请勿转载和采集!