Making HTTP requests in Javascript using Fetch

February 02, 2019

Making HTTP requests is what many struggle with starting out with Javascript. There are many alternatives to use. In this article we explain how to use Axios, which is library that lets you make HTTP requests using Javascript.

Now let's talk about Fetch. Fetch is a new built-in Javascript API that lets you make network requests.

How do I use it?

To make a call to a page that'll return a JSON response:

  .then(response => response.json())
  .then(json => console.log('JSON RESPONSE', json))
  .catch(e => {
    console.log('Error', e)

For HTML or text response, do this:

  .then(response => response.text())
  .then(body => console.log('BODY', body))

Note: Fetch is not supported in all browsers

To see a list of browsers that support Fetch you can read this page on Mozilla docs. IE is not supported at all

But you can fix that...

Github created a polyfill for Fetch, which'll mean you can use Fetch with the polyfill and be sure that you'll support all of the browsers we care about.

How do I get the polyfill?

Install the polyfill library:

npm install whatwg-fetch --save

Import the library in your project: (Importing the library will automatically apply the polyfill to window.fetch)

import 'whatwg-fetch'

Now use fetch as shown above