A Practical guide to use Fetch API – Nivesh's blog
Published on

A Practical guide to use Fetch API

Authors
Table of contents

Introduction

Fetch is a promise based Javascript API for making asynchronous HTTP requests. It is a clean, simple, powerful and a flexible API to get/send data from/to a server.

A simple GET request example using Fetch API

fetch('https://jsonplaceholder.typicode.com/posts')
  .then(function(response) {
    //
  })
  .catch(function(error) {
    //
  });

The Response returned by the fetch() method contains the information about the request and the response of the network request including headers, status code, and status message. The body of Response has a few methods:

  • clone() - As the method implies this method creates a clone of the response.
  • redirect() - This method creates a new response but with a different URL.
  • arrayBuffer() - In here we return a promise that resolves with an ArrayBuffer.
  • formData() - Also returns a promise but one that resolves with FormData object.
  • blob() - This is one resolves with a Blob.
  • text() - In this case it resolves with a string.
  • json() - Lastly we have the method to that resolves the promise with JSON.
fetch('https://jsonplaceholder.typicode.com/posts')
  .then(function(response) {
    // get response headers
    console.log(response.headers.get('content-type'));

    console.log(response.headers.get('expires'));

    // HTTP response status code
    console.log(response.status);

    // shorthand for `status` between 200 and 299
    console.log(response.ok);

    // status message of the response e.g. `OK`
    console.log(response.statusText);

    // check if there was a redirect
    console.log(response.redirected);

    // get the response type (e.g., `basic`, `cors`)
    console.log(response.type);

    // the full path of the resource
    console.log(response.url);
  })
  .catch(function(error) {
    //
  });

  Here is how you can use Fetch to request JSON data from server:

fetch('https://jsonplaceholder.typicode.com/posts')
  .then(function(response){
    return response.json();
  })
  .then(function(data) {
    // data here is JSON object
    console.log(data);
  })
  .catch(function(error) {
    //
  });

How to use Fetch API to send POST requests

Fetch is not just for GET requests. It can be used for all other request types like POST, PUT, PATCH, DELETE etc. Here's an example of POST type request:

fetch('https://jsonplaceholder.typicode.com/posts', {
    method: 'POST',
    body: JSON.stringify({
      title: 'foo',
      body: 'bar',
      userId: 1
    })
  })
  .then(function(response){
    return response.json();
  })
  .then(function(data) {
    // data here is JSON object
  })
  .catch(function(error) {
    //
  });

Make sure you Stringify your JSON data before sending to server.

Set Headers for Fetch request

Setting up headers for your request is pretty easy. One of the easiest way is to pass a headers objects along with the request.

fetch('https://jsonplaceholder.typicode.com/posts', {
    method: 'POST',
    body: JSON.stringify({
      title: 'foo',
      body: 'bar',
      userId: 1
    }),
    headers: {
      "Content-type": "application/json"
    }
  })
  .then(function(response){
    return response.json();
  })
  .then(function(data) {
    // data here is JSON object
  })
  .catch(function(error) {
    //
  });

Cookies

Fetch doesn't send cookies by default and if you need to send cookies along with the request, you will have to enable it explicitly. Here's how:

fetch('https://jsonplaceholder.typicode.com/posts', {
    credentials: 'include'
  })
  .then(function(response) {
    //
  })
  .catch(function(error) {
    //
  });

Error Handling

We can use the catch() method of the promise to intercept any error that is thrown during the execution of the request. However, no error will be thrown if the request hits the server and comes back, regardless of what response was returned by the server. The promise returned by the fetch() doesn't reject HTTP errors even if the HTTP response code is 404 or 500.

fetch('https://jsonplaceholder.typicode.com/some-invalid-path', {
    credentials: 'include'
  })
  .then(function(response) {

    if(response.ok)
    {
      return response.json();
    }

    return Promise.reject(response.status);
  })
  .catch(function(error) {
    //
    console.error(error)
  });

I've got more coming...

Want to hear from me when I add new post? Sign up for my newsletter and I'll email you every time I post a new article. (I'll never share your email and only send you updates about new articles.)