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

What is the Fetch API and how do I use it?

Asked on Aug 18, 2024

Answer

The Fetch API is a modern interface that allows you to make network requests similar to XMLHttpRequest (XHR) but with a more powerful and flexible feature set. It is promise-based, making it easier to work with asynchronous operations.
<!-- BEGIN COPY / PASTE -->
        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(data);
            })
            .catch(error => {
                console.error('There was a problem with the fetch operation:', error);
            });
        <!-- END COPY / PASTE -->
Additional Comment:
  • The Fetch API uses promises, which means you can use "then" and "catch" for handling responses and errors.
  • The "fetch" function takes a URL as an argument and returns a promise that resolves to the response.
  • Always check "response.ok" to ensure the request was successful before processing the data.
  • Use "response.json()" to parse the JSON data from the response.
✅ Answered with JavaScript best practices.
← Back to All Questions