What are the differences between XMLHttpRequest and fetch() in JavaScript and browsers?

Answer

XMLHttpRequest and fetch() are both used to make HTTP requests in JavaScript, but they have several key differences:

1. API Simplicity and Syntax:

Example:

var xhr = new XMLHttpRequest();
xhr.open('GET', '/example', true);
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    console.log(xhr.responseText);
  }
};
xhr.send();

Example:

fetch('/example')
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error(error));

2. Promise-Based vs Callback-Based:

3. Handling of Response Types:

Example:

Skopiuj kod
fetch('/example')
.then(response => response.json())
.then(data => console.log(data));

4. CORS Handling:

5. Error Handling:

Example:

xhr.onerror = function () {
  console.log('Error occurred');
};
fetch('/example')
  .then((response) => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .catch((error) => console.error('Fetch error:', error));

6. Support for Streaming:

fetch('/largefile').then((response) => {
  const reader = response.body.getReader();
  // Handle the streaming data
});

7. Timeouts:

Example:

const controller = new AbortController();
const signal = controller.signal;

fetch('/example', { signal })
  .then((response) => response.json())
  .catch((err) => {
    if (err.name === 'AbortError') {
      console.log('Request timed out');
    }
  });

setTimeout(() => controller.abort(), 5000); // Abort after 5 seconds

8. Browser Compatibility:

9. Request Cancellation:

Conclusion:

MDN Web Docs on XMLHttpRequest

MDN Web Docs on Fetch API