雖然 fetch 已成主流,但在維護老專案或需攔截進度事件、超時控制、同步請求(罕見)時,仍需 XMLHttpRequest。本文提供標準工廠函數、TypeScript 類型、進度監聽、超時、取消封裝,並對比 Fetch 優缺點。
function createXHR() {
if (typeof XMLHttpRequest !== 'undefined') return new XMLHttpRequest();
// IE6/ActiveX 回退(現代專案可刪除)
const versions = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP'];
for (const v of versions) {
try { return new ActiveXObject(v); } catch (e) {}
}
throw new Error('XMLHttpRequest not supported');
}
interface XHROptions {
method?: string;
headers?: Record<string, string>;
body?: Document | BodyInit | null;
timeout?: number; // ms
onProgress?: (e: ProgressEvent) => void;
responseType?: XMLHttpRequestResponseType;
signal?: AbortSignal; // 現代取消標準
}
function request(url: string, opts: XHROptions = {}): Promise<XMLHttpRequest> {
return new Promise((resolve, reject) => {
const xhr = createXHR();
const { method = 'GET', headers = {}, body = null, timeout = 0, onProgress, responseType = 'json', signal } = opts;
xhr.open(method, url, true);
xhr.responseType = responseType;
Object.entries(headers).forEach(([k, v]) => xhr.setRequestHeader(k, v));
if (timeout) xhr.timeout = timeout;
if (onProgress) xhr.addEventListener('progress', onProgress);
if (signal) {
signal.addEventListener('abort', () => xhr.abort());
}
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) resolve(xhr);
else reject(new Error(`HTTP ${xhr.status}: ${xhr.statusText}`));
};
xhr.onerror = () => reject(new Error('Network error'));
xhr.ontimeout = () => reject(new Error('Timeout'));
xhr.send(body);
});
}
// GET
request('/api/users').then(xhr => console.log(xhr.response));
// POST JSON
request('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Alice' })
}).then(xhr => console.log(xhr.response));
// 上傳進度
request('/upload', {
method: 'POST',
body: formData,
onProgress: e => console.log(`${Math.round(e.loaded/e.total*100)}%`)
});
// 超時 + AbortController 取消
const ctrl = new AbortController();
request('/slow', { timeout: 5000, signal: ctrl.signal });
setTimeout(() => ctrl.abort(), 3000);
| 特性 | Fetch | XHR |
|---|---|---|
| Promise 原生 | ✅ | 需封裝 |
| 請求進度 | ❌(需 ReadableStream) | ✅ progress 事件 |
| 上傳進度 | ❌ | ✅ upload.onprogress |
| 超時控制 | 需 AbortController + setTimeout | ✅ timeout 屬性 |
| 同步請求 | ❌ | ✅(極不推薦) |
| Cookie 自動攜帶 | 需 credentials: 'include' | 同源自動 |
| 取消請求 | AbortController | xhr.abort() |
**結論**:新專案優先 fetch + ky/axios 封裝;需上傳進度、超時、舊瀏覽器兼容時用 XHR。