Understanding Axios POST requests

Understanding Axios POST requests

What exactly is Axios?

Quick summary,

According to the documentation,

Axios is a promise-based HTTP Client for node.js and the browser. It is isomorphic (= it can run in the browser and nodejs with the same codebase). On the server-side it uses the native node.js http module, while on the client (browser) it uses XMLHttpRequests.

In this tutorial, we’re going to get a better understanding of using axios to make POST requests. We’ll use axios as a JavaScript library to perform HTTP requests in Node.js and therefore in this process master using axios for POST requests.

A few prerequisites before learning axios would be basic JavaScript, Ajax fundamentals, array, .map, promises and callback functions.

Goal

At the end of this tutorial, users would be able to make POST requests seamlessly using axios.

But first, what are HTTP request libraries?

HTTP request libraries provide a clean and simplified interface to make HTTP requests. The spirit of this library is to make it trivial to do easy things with HTTP requests. It can accomplish the most common use cases for an HTTP client, but does not aim to be a complete HTTP client implementation. Examples are: Axios, Fetch, Needle, Got, Node-fetch.

  • Why use axios?

It supports the Promise API that is native to JS ES6. It can be used intercept HTTP requests and responses and enables client-side protection against XSRF (Cross site request forgery). It also has the ability to cancel requests.

Other JavaScript HTTP request libraries similar to axios

  • Axios vs Fetch

We'd review two highlights of Fetch API and Axios to see the best option for HTTP requests.

  • Error Handling : Error handling with Axios is easy because bad responses (such as 404 or 500) will end up causing the Promise to be rejected by throwing an exception. Therefore, to handle 404 or 400 errors with Axios, you need to use the catch() block as shown below.
axios
  .get("localhost:3000/api/home")
  .then(response => {
    console.log("response", response)
  })
  .catch(error => {
    if (error.response) {
      // The request was made and the server responded with a status code that falls out of the range of 200
      // Something like 4xx or 500
      console.log(error.response.data)
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of http.ClientRequest in node.js
      console.log(error.request)
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log("Error", error.message)
    }
    console.log(error.config)
  })

When using fetch(), you need to read the response object since bad responses are still resolved using the then() method. A Fetch API Promise will be rejected only if the request cannot be completed in a scenario like a network failure.

fetch("localhost:3000/api/home")
  .then(response => {
    if (!response.ok) {
      throw Error(response.statusText)
    }
    return response.json()
  })
  .then(data => {
    console.log(data)
  })
  .catch(error => console.error(error))
  • Simultaneous Requests

Both Axios and Fetch API can handle multiple requests in parallel. Axios uses the axios.all() method that allows passing an array of requests. Then assign the properties of the response array to distinct variables using axios.spread() as shown here.

axios.all([
  axios.get('http://localhost:3000/api/home'), 
  axios.get('http://localhost:3000/api/page')
])
.then(axios.spread((obj) => {
  // Both requests are now complete
  console.log(obj[0].data.login);
  console.log(obj[1].data.login);
}));

With Fetch API, you can use the built-in Promise.all() method to accomplish the same by passing all fetch requests to Promise.all() as an array. Next, you can use an async function to handle the response as follows.

Promise.all([
  fetch('http://localhost:3000/api/home'),
  fetch('http://localhost:3000/api/page')
])
.then(async([res1, res2]) => {
  const obj1 = await res1.json();
  const obj2 = await res2.json();
  console.log(obj1.login);
  console.log(obj2.login);
})
.catch(error => {
  console.log(error);
});

This comparison demonstrates that Axios keeps the code minimal for applications that require efficient error handling or HTTP interceptions. it supports almost all modern browsers and NodeJS environments. On the other hand, Fetch API isn’t far off either as a native method supported by all the major browsers (it doesn’t support Internet explorer).

Making a POST request with Axios

  • First, axios has to be installed using either npm, bower, yarn or a manual installation.

  • Using npm

$ npm install axios
  • Using bower
$ yarn add axios
  • Using yarn
$ yarn add axios
  • Next, perform a GET request for API keys
    axios({
    method: 'get',
    url: 'http://bit.ly/2mTM3nY',
    responseType: 'stream'
    })
    .then(function (response) {
     response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
    });
    

- Next we'd perform a POST request

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  • Axios also performs multiple concurrent requests
function getUserAccount() {
  return axios.get('/user/12345');
}

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

Promise.all([getUserAccount(), getUserPermissions()])
  .then(function (results) {
    const acct = results[0];
    const perm = results[1];
  });

Some Instance methods for Axios

axios#request(config)

axios#get(url[, config])

axios#delete(url[, config])

axios#head(url[, config])

axios#options(url[, config])

axios#post(url[, data[, config]])

axios#put(url[, data[, config]])

axios#patch(url[, data[, config]])

axios#getUri([config])

We have now come to the end of understanding Axios POST requests. I hope this article helped to explain Axios POST requests.

3584066.jpg

Thank you for reading!