DEV Community

Cover image for JSByte: How to use fetch API to make AJAX requests in JavaScript?
Shruti Kapoor
Shruti Kapoor

Posted on

JSByte: How to use fetch API to make AJAX requests in JavaScript?

I will be sharing bite sized learnings about JavaScript regularly in this series. This series will cover JS fundamentals, browsers, DOM, system design, domain architecture and frameworks.


Fetch is an interface for making an AJAX request in JavaScript. It is implemented widely by modern browsers and is used for calling an API.

const promise = fetch(url, [options])

Enter fullscreen mode Exit fullscreen mode

Calling fetch returns a promise, with Response object. The promise is rejected if there is a network error, and resolved if there is no problem connecting to the server and the server responded with a status code. This status code could be 200s, 400s or 500s.

A sample FETCH request -


fetch(url)
.then(response => response.json())
.catch(err => console.log(err))

Enter fullscreen mode Exit fullscreen mode

The request is sent as a GET by default. To send a POST / PATCH / DELETE / PUT you can use the method property as part of options parameter. Some other possible values options can take -

  • method: such as GET, POST, PATCH
  • headers: Headers object
  • mode: such as cors, no-cors, same-origin
  • cache: cache mode for request
  • credentials
  • body

Check out the full list of available options here

This example demonstrates the usage of fetch to call an API and to get a list of git repositories.

const url = 'https://api.github.com/users/shrutikapoor08/repos';

fetch(url)
  .then(response => response.json())
  .then(repos => {
    const reposList = repos.map(repo => repo.name);
    console.log(reposList);
  })
.catch(err => console.log(err))

Enter fullscreen mode Exit fullscreen mode

To send a POST request, here's how method parameter can be used with async / await syntax.

const params = {
id: 123
}

const response = await fetch('url', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(params)
});

const data = await response.json();

Enter fullscreen mode Exit fullscreen mode

Interested in more JSBytes? Sign up for the newsletter

Top comments (0)