Journal for Developers

Axios: Promise based HTTP client for the Browser and NodeJS

0 155

Axios: Promise based HTTP client for the browser and NodeJS

#Features

  • Make XMLHttpRequests from the browser
  • Make http requests from node.js
  • Supports the Promise API
  • Intercept request and response
  • Transform request and response data
  • Cancel requests
  • Automatic transforms for JSON data
  • Client side support for protecting against XSRF

#Installing

Using npm:

$ npm install axios

Using bower:

$ bower install axios

Using CDN:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

 

#Example

Performing a GET request
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// Optionally the request above could also be done as
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
Performing a POST request
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
Performing multiple concurrent requests
function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // Both requests are now complete
  }));

 

In the next journal, we will be talking more in depth about the API usage of Axios.

Image Courtesy: InternetDevels

Subscribe to our Journal

Join our mailing list to receive the latest news and updates from our team.

You have Successfully Subscribed!