DEV Community

Derrick TheCodeholic
Derrick TheCodeholic

Posted on


Getting Started With Axios and fetch()

fetch() allows you to make network requests similar to XMLHttpRequest (XHR). The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API, avoiding callback hell and having to remember the complex API of XMLHttpRequest.
Using Fetch API is really simple. Just pass the URL, the path to the resource you want to fetch, to fetch() method:

    .then(response => {
        // handle response data
    .catch(err => {
        // handle errors

Lets look at two examples, one using XMLHttpRequest and the other with fetch().

function reqListener() {
  var data = JSON.parse(this.responseText);

function reqError(err) {
  console.log('Fetch Error :-S', err);

var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.onerror = reqError;'get', './api/some.json', true);

Our fetch request looks a little like this:

    function(response) {
      if (response.status !== 200) {
        console.log('Looks like there was a problem. Status Code: ' +

      // Examine the text in the response
      response.json().then(function(data) {
  .catch(function(err) {
    console.log('Fetch Error :-S', err);

We start by checking that the response status is 200 before parsing the response as JSON.

The response of a fetch() request is a Stream object, which means that when we call the json() method, a Promise is returned since the reading of the stream will happen asynchronously.
Lets use GET Request, POST Request and DELETE Request.

GET request
By default, the Fetch API uses GET method for asynchronous requests. Let's use the Reqres REST API(A hosted REST-API ready to respond to your AJAX requests.) to retrieve a list of users using GET request:

    .then(res => res.json())
    .then(res => { => {
            console.log(`${}: ${user.first_name} ${user.last_name}`);

This will output the following from Reqres REST API:

1: George Bluth
2: Janet Weaver
3: Emma Wong

POST Request

const user = {
    first_name: 'Deliic',
    last_name: 'Mugambi',
    job_title: 'Software Engineer'

const options = {
    method: 'POST',
    body: JSON.stringify(user),
    headers: {
        'Content-Type': 'application/json'

fetch('', options)
    .then(res => res.json())
    .then(res => console.log(res));

The Reqres API sends us the body data back with an ID and created timestamp attached
DELETE Request

const options = {
    method: 'DELETE',
    headers: {
        'Content-Type': 'application/json'

fetch('', options)
    .then(res => {
        if (res.ok) {
            return Promise.resolve('User deleted.');
        } else {
            return Promise.reject('An error occurred.');
    .then(res => console.log(res));

Axios is a popular, promise-based HTTP client that sports an easy-to-use API and can be used in both the browser and Node.js.
the most common way to install Axios is via the npm package manager:

npm i Axios

After installing you need to include it in your code like below:

import axios from 'axios';

Making Requests

  method: 'post',
  url: '/login',
  data: {
    user: 'brunos',
    lastName: 'ilovenodejs'

Here, we’re telling Axios which HTTP method we’d like to use (e.g. GET/POST/DELETE etc.) and which URL the request should be made to.

We’re also providing some data to be sent along with the request in the form of a simple JavaScript object of key/value pairs. By default, Axios will serialize this as JSON and send it as the request body.
Receiving a Response

  .then(response => console.log(response))
  .catch(error => console.log(error));

Once you make a request, Axios returns a promise that will resolve to either a response object or an error object
The response object
When the request is successful, your then() callback will receive a response object with the following properties:

data: the payload returned from the server. By default, Axios expects JSON and will parse this back into a JavaScript object for you.
status: the HTTP code returned from the server.
statusText: the HTTP status message returned by the server.
headers: all the headers sent back by the server.
config: the original request configuration.
request: the actual XMLHttpRequest object (when running in a browser)
The error object
If there’s a problem with the request, the promise will be rejected with an error object containing at least some of the following properties:

message: the error message text.
response: the response object (if received) as described in the previous section.
request: the actual XMLHttpRequest object (when running in a browser).
config: the original request configuration.

Axios allows you to provide functions to transform the outgoing or incoming data, in the form of two configuration options you can set when making a request: transformRequest and transformResponse. Both properties are arrays, allowing you to chain multiple functions that the data will be passed through.

Any functions passed to transformRequest are applied to PUT, POST and PATCH requests. They receive the request data, and the headers object as arguments and must return a modified data object.

const options = {
  transformRequest: [
    (data, headers) => {
      // do something with data
      return data;

While transforms let you modify outgoing and incoming data, Axios also allows you to add functions called interceptors. Like transforms, these functions can be attached to fire when a request is made, or when a response is received.

// Add a request interceptor
axios.interceptors.request.use((config) => {
    // Do something before request is sent
    return config;
  }, (error) => {
    // Do something with request error
    return Promise.reject(error);

// Add a response interceptor
axios.interceptors.response.use((response) => {
    // Do something with response data
    return response;
  }, (error) => {
    // Do something with response error
    return Promise.reject(error);

Interceptors have some important differences from transforms. Instead of just receiving the data or headers, interceptors receive the full request config or response object.

When creating interceptors, you can also choose to provide an error handler function that allows you to catch any errors and deal with them appropriately

Top comments (0)

An Animated Guide to Node.js Event Loop

>> Check out this classic DEV post <<