2025年6月9日10:23:02
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* 封装 XMLHttpRequest 请求
|
||||
* @param {string} method - 请求方法 ('GET' 或 'POST')
|
||||
* @param {string} url - 请求的 URL
|
||||
* @param {Object} params - 请求参数(对于 GET 请求会拼接到 URL,对于 POST 请求放在请求体中)
|
||||
* @param {Object} headers - 请求头对象(键值对形式)
|
||||
* @returns {Promise} 返回一个 Promise,解析为响应数据或拒绝为错误
|
||||
*/
|
||||
export function httpRequest(method, url, params, headers) {
|
||||
return new Promise(function(resolve, reject) {
|
||||
let xhr = new XMLHttpRequest();
|
||||
// xhr.withCredentials = true;
|
||||
let queryString = '';
|
||||
|
||||
// 将 params 转为查询字符串(仅对 GET 请求有效)
|
||||
if (params && method.toUpperCase() === 'GET') {
|
||||
queryString = Object.keys(params).map(function(key) {
|
||||
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
|
||||
}).join('&');
|
||||
url += (url.indexOf('?') === -1 ? '?' : '&') + queryString;
|
||||
}
|
||||
|
||||
xhr.open(method.toUpperCase(), url, true);
|
||||
|
||||
// 设置请求头
|
||||
if (headers) {
|
||||
for (let key in headers) {
|
||||
if (headers.hasOwnProperty(key)) {
|
||||
xhr.setRequestHeader(key, headers[key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 监听请求状态变化
|
||||
xhr.onreadystatechange = function() {
|
||||
if (xhr.readyState === 4) { // 请求完成
|
||||
if (xhr.status >= 200 && xhr.status < 300) { // 请求成功
|
||||
try {
|
||||
let response = JSON.parse(xhr.responseText); // 尝试解析为 JSON
|
||||
resolve(response);
|
||||
} catch (e) {
|
||||
resolve(xhr.responseText); // 如果不是 JSON,返回原始文本
|
||||
}
|
||||
} else {
|
||||
reject({
|
||||
status: xhr.status,
|
||||
statusText: xhr.statusText,
|
||||
response: xhr.responseText
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
xhr.onerror = function() {
|
||||
reject({
|
||||
status: xhr.status,
|
||||
statusText: xhr.statusText
|
||||
});
|
||||
};
|
||||
|
||||
// 发送请求(对于 POST 请求需要发送 JSON 格式的参数)
|
||||
if (method.toUpperCase() === 'POST') {
|
||||
xhr.setRequestHeader('Content-Type', 'application/json');
|
||||
xhr.send(JSON.stringify(params));
|
||||
} else {
|
||||
xhr.send();
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user