JavaScript Fetch API to make HTTP requests

The Fetch API is a better way to make HTTP requests in front-end applications. It is quite similar to the XMLHTTPRequest. The Fetch API provides a method called fetch() to make the HTTP requests.

The fetch() method

The fetch() method takes the API URL as the first parameter. This method returns a Promise, so we need to consume it to get the response.

fetch('https://jsonplaceholder.typicode.com/posts')
.then((res) => console.log(res));

Here the response returned is a Response object which contains some useful data. Take a look at the Response object below.

Response object

We can access the headers and status properties of the HTTP response to get more details.

fetch('https://jsonplaceholder.typicode.com/posts')
.then((res) => {
  const headers = res.headers;
  const status = res.status; // returns http status like 200, 404 etc.
  const isStatusOk = res.ok; // returns true if status is between 200 and 299.
});

Now to extract the response body as JSON data from the Response object, we can use the json() method. The json() method returns a Promise which can be consumed to get the response body.

fetch('https://jsonplaceholder.typicode.com/posts')
.then((res) => res.json())
.then((data) => console.log(data));
// prints json data to console

There are a variety of utility methods available in the Response object to parse the response body in respective formats like JSON, text, blob, formData, or arrayBuffer. All these methods return Promise.

  • json() – get the response in JSON format.
  • text() – get the response in text format.
  • blob() – get the response in Blob format.
  • formData() – get the response in FormData format.
  • arrayBuffer() – get the response in ArrayBuffer format.

To get the response in text format, try the below code:

fetch('https://jsonplaceholder.typicode.com/posts')
.then((res) => res.text())
.then((data) => console.log(data));
// prints text formatted data to console

HTTP post request using fetch()

The fetch() method accepts a second optional parameter i.e. options, which is an object containing the data like method type, headers, body, etc. The fetch() method by default sends GET request, so we need to manually set the method type for other requests.

const options = {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ title: 'new', post: 'new post' })
};

fetch('https://jsonplaceholder.typicode.com/posts', options)
.then((res) => res.json())
.then((data) => console.log(data));

The Content-Type of headers is set to text/plain by default. To send JSON data, set it to application/json. Similarly, set it for other data types.

Handling Errors

We can chain a catch() method with fetch() to catch server errors but this is not enough.

The fetch() method throws an error only when there is any network error or invalid host address etc. If there is any error with a response and bad HTTP status, then it is treated as a successful response and it doesn’t make it to the catch() method.

Let’s see one example using a non-existing host address. Here the catch() method will execute as the fetch() method considers it as an error.

fetch('https://invalid-host-address/posts')
.then((res) => res.json())
.then((data) => console.log(data))
.catch((error) => console.log('Error:', error));
// Error: TypeError: Failed to fetch

Now let’s see one example with a valid host and non-existing path. Here we will get 404 error but this will be considered a successful response and catch() method will not execute.

fetch('https://jsonplaceholder.typicode.com/no-such-page')
.then((res) => { 
  console.log(res.status); // 404
  return res.json();
})
.then(data => console.log('Success:', data))
.catch(error => console.log('Error:', error));
// Success: {}

So to catch such technical errors, we need to manually check the status of the response and return an Error object if it is a bad response. We can check If the response status is >=400 then it is a bad response or we can simply use the ok property which will return false for bad responses.

fetch('https://jsonplaceholder.typicode.com/no-such-page')
.then((res) => { 
  if(!res.ok) {
    throw new Error('An Error Occured');
  }
  return res.json();
})
.then((data) => console.log('Success:', data))
.catch((error) => console.log('Failed:', error));

Abort fetch request

To abort/ cancel a fetch request, we can use the AbortController object. First, we need to pass the signal key in the options object of fetch() and assign it with the signal value of the AbortController instance.

const controller = new AbortController();

fetch('https://jsonplaceholder.typicode.com/posts', {
  signal: controller.signal
})
.then((res) => res.json())
.then((data) => console.log(data))
.catch((error) => console.log('Error:', error));

Now, to abort the request, we need to call the abort() method on the controller instance.

controller.abort();

Fetch using async and await

As we deal with Promises in fetch, we can also make use of async/await to handle those Promises in a more cleaner and readable way.

const fetchHandler = async () => {
  const response = await fetch('https://jsonplaceholder.typicode.com/posts');
  const posts = await response.json();
  console.log(posts);
}

fetchHandler();

Error Handling

We can use try…catch block to handle errors in async/await.

const fetchHandler = async () => {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts');
    const posts = await response.json();
    if (!response.ok) {
      const error = new Error('An Error Occured');
      error.details = posts;
      throw error;
    }
    console.log(posts);
  } catch(e) {
    console.log(e.message); // An Error Occurred
    console.log(e.details); // prints response got from server
  }
}

fetchHandler();

In case of a bad response, posts will contain the error details returned by the server. We can use these error details to get more information about the error.

See next

4 thoughts on “JavaScript Fetch API to make HTTP requests

  1. Good tidings, Generally I never remark on online journals yet your article is persuading to the point that I never stop myself to say something regarding it. You’re working effectively, Keep it up. You can look at this article, may be of help 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *