What is XMLHttpRequest and why would you still use it over fetch() today?
Short answer
XHR is the older, event-based API for HTTP requests. Unlike fetch(), it natively supports upload/download progress events and can be aborted synchronously without needing the AbortController API — some libraries and progress-bar-driven upload UIs still rely on XHR for these…
Advertisement
AModel answer
XHR is the older, event-based API for HTTP requests. Unlike fetch(), it natively supports upload/download progress events and can be aborted synchronously without needing the AbortController API — some libraries and progress-bar-driven upload UIs still rely on XHR for these reasons.
const xhr = new XMLHttpRequest();
xhr.open('POST', '/upload');
xhr.upload.onprogress = (e) => console.log(`${e.loaded}/${e.total}`);
xhr.onload = () => console.log(xhr.responseText);
xhr.send(formData);Real-world example
Showing a real-time upload progress bar for a large file, which fetch() can't do natively for uploads.
Likely follow-ups
- Does fetch() have any modern way to track upload progress, given this limitation?
Related topics