fix(utils): 修复请求工具中的XMLHttpRequest配置问题

- 移动XMLHttpRequest实例化到方法开头避免重复创建
- 删除被注释掉的旧请求完成事件处理代码
- 修正请求错误和中止事件的错误处理逻辑
- 移除重复的xhr.open调用确保正确的HTTP方法设置
This commit is contained in:
2026-02-01 22:07:43 +08:00
parent fda283198d
commit f06d6e5a7e

View File

@@ -82,6 +82,9 @@ class Request {
*/ */
createXHRWithProgress(url, config, onProgress, onDownloadProgress) { createXHRWithProgress(url, config, onProgress, onDownloadProgress) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(config.method || "POST", url);
// 设置请求头 // 设置请求头
if (config.headers) { if (config.headers) {
Object.keys(config.headers).forEach((key) => { Object.keys(config.headers).forEach((key) => {
@@ -89,8 +92,6 @@ class Request {
}); });
} }
const xhr = new XMLHttpRequest();
// 监听上传进度 // 监听上传进度
xhr.upload.addEventListener("progress", function (event) { xhr.upload.addEventListener("progress", function (event) {
if (event.lengthComputable) { if (event.lengthComputable) {
@@ -103,14 +104,6 @@ class Request {
} }
}); });
// 请求完成
// xhr.addEventListener("load", function () {
// if (xhr.status >= 200 && xhr.status < 300) {
// const response = JSON.parse(xhr.responseText);
// resolve(xhr);
// }
// });
// 请求完成处理 // 请求完成处理
xhr.addEventListener("load", () => { xhr.addEventListener("load", () => {
if (xhr.status >= 200 && xhr.status < 300) { if (xhr.status >= 200 && xhr.status < 300) {
@@ -142,16 +135,15 @@ class Request {
// 请求错误 // 请求错误
xhr.addEventListener("error", function () { xhr.addEventListener("error", function () {
console.error("网络错误"); console.error("网络错误");
if (onError) onError(new Error("网络错误")); reject(new Error("网络错误"));
}); });
// 请求中止 // 请求中止
xhr.addEventListener("abort", function () { xhr.addEventListener("abort", function () {
console.log("上传已取消"); console.log("上传已取消");
if (onError) onError(new Error("上传已取消")); reject(new Error("上传已取消"));
}); });
xhr.open("POST", url);
xhr.send(config.body); xhr.send(config.body);
return xhr; // 返回 xhr 对象以便后续控制 return xhr; // 返回 xhr 对象以便后续控制