JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

How does XMLHttpRequest differ from Fetch API?

Asked on Aug 19, 2024

Answer

The XMLHttpRequest and Fetch API are both used to make network requests in JavaScript, but they have some key differences in usage and features.
<!-- BEGIN COPY / PASTE -->
        // Using XMLHttpRequest
        const xhr = new XMLHttpRequest();
        xhr.open("GET", "https://api.example.com/data", true);
        xhr.onload = function() {
            if (xhr.status === 200) {
                console.log("XMLHttpRequest Response:", xhr.responseText);
            }
        };
        xhr.send();

        // Using Fetch API
        fetch("https://api.example.com/data")
            .then(response => {
                if (!response.ok) {
                    throw new Error("Network response was not ok");
                }
                return response.json();
            })
            .then(data => console.log("Fetch API Response:", data))
            .catch(error => console.error("Fetch API Error:", error));
        <!-- END COPY / PASTE -->
Additional Comment:
  • The Fetch API is more modern and returns a Promise, making it easier to work with asynchronous code using then() and catch() methods.
  • XMLHttpRequest is older and uses a callback pattern, which can be more cumbersome and harder to read.
  • Fetch API provides a more powerful and flexible feature set, such as streaming and handling requests and responses with more control.
  • Error handling in Fetch requires checking the response.ok property, while XMLHttpRequest uses status codes directly.
✅ Answered with JavaScript best practices.
← Back to All Questions