Published: September 22 2021

Fetch + Vanilla JS - Check if HTTP Response is JSON in JavaScript

This is a quick example of how to check that the response type is JSON for an HTTP request sent the Fetch API (fetch()) which comes bundled with all modern browsers.

The solution is to check that the response HTTP Content-Type header includes the text 'application/json' like this:
const isJson = response.headers.get('content-type')?.includes('application/json');


GET request with JSON response check

This sends an HTTP GET request to the Reqres api which is a fake online REST api used for testing, it includes an /api/users route that supports GET requests and returns an array of users plus the total number of users. This example writes the total from the response to the #get-request .total element so it's displayed on the page.

JSON Check

The fetch .then() callback is passed the HTTP response object when the request is completed, the function checks if the response type is JSON before parsing the response body with the response.json() method, because calling response.json() will cause an error if the response doesn't contain JSON data.

Error Handling

The fetch() function will automatically throw an error for network errors but not for HTTP errors such as 4xx or 5xx responses. For HTTP errors we can check the response.ok property to see if the request failed and reject the promise ourselves by calling return Promise.reject(error);. This approach means that both types of failed requests - network errors and http errors - can be handled by a single catch() block.

// Fetch GET request that checks response is JSON
const element = document.querySelector('#get-request .total');
fetch('https://reqres.in/api/users')
    .then(async response => {
        const isJson = response.headers.get('content-type')?.includes('application/json');
        const data = isJson ? await response.json() : null;

        // check for error response
        if (!response.ok) {
            // get error message from body or default to response status
            const error = (data && data.message) || response.status;
            return Promise.reject(error);
        }

        element.innerHTML = data?.total;
    })
    .catch(error => {
        element.parentElement.innerHTML = `Error: ${error}`;
        console.error('There was an error!', error);
    });

Run the example Fetch GET request on StackBlitz at https://stackblitz.com/edit/fetch-check-response-is-json

 


Need Some Fetch Help?

Search fiverr for freelance Fetch developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by