diff --git a/frontend/src/utils/request.ts b/frontend/src/utils/request.ts index b3d972b..aed6743 100644 --- a/frontend/src/utils/request.ts +++ b/frontend/src/utils/request.ts @@ -82,6 +82,9 @@ class Request { */ createXHRWithProgress(url, config, onProgress, onDownloadProgress) { return new Promise((resolve, reject) => { + const xhr = new XMLHttpRequest(); + xhr.open(config.method || "POST", url); + // 设置请求头 if (config.headers) { Object.keys(config.headers).forEach((key) => { @@ -89,8 +92,6 @@ class Request { }); } - const xhr = new XMLHttpRequest(); - // 监听上传进度 xhr.upload.addEventListener("progress", function (event) { 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", () => { if (xhr.status >= 200 && xhr.status < 300) { @@ -142,16 +135,15 @@ class Request { // 请求错误 xhr.addEventListener("error", function () { console.error("网络错误"); - if (onError) onError(new Error("网络错误")); + reject(new Error("网络错误")); }); // 请求中止 xhr.addEventListener("abort", function () { console.log("上传已取消"); - if (onError) onError(new Error("上传已取消")); + reject(new Error("上传已取消")); }); - xhr.open("POST", url); xhr.send(config.body); return xhr; // 返回 xhr 对象以便后续控制