https://www.sitepoint.com/axios-beginner-guide/

This week I decided to write about Axios for JavaScript. We are using Axios on our front end. So I thought it could be helpful to read an article about Axios, and learn more about what Axios does and how it works.

Axios can be used on backend node.js applications. And used in JavaScript files/ frameworks like Vue, React, and Angular. One of the most common uses of Axios is making HTTP requests to send, receive, or save data. Data passed in post operations is conveniently sent in JSON format. Below is an example of an axios HTTP request method.

axios({
  method: 'post',
  url: '/login',
  data: {
    user: 'brunos',
    lastName: 'ilovenodejs'
  }
});

Axios also has a convenient way to receive responses. Axios returns a promise that is either a response or an error method. A response object is returned with a successful call, and the .then() function is called. The response object has data, which is the payload in JSON. The status in the form of an HTTP code. The status text, which is an HTTP message. Headers, returned by the server. The original request information. And the HTTP request in the XMLHTTPRequest object format.

If an Axios request returns an error, the promise will be rejected and an error object is returned. An error object includes: an error message, a response object, a request, and the original request.

axios.get('/product/9')
  .then(response => console.log(response))
  .catch(error => console.log(error));

To better understand Axios, it is worth explaining what a JavaScript promise is, and why programmers use them. Promises are used to handle asynchronous functions in JavaScript. Promises may return a value or payload, or an error message. Each promise has a state. A promise can take three different states. fufilled, rejected, and pending. In the code below process will not execute until fetch executes. And handleErrors will not execute until save has executed. .catch will handle erros within process() and save().

fetch(url)
.then(process)
.then(save)
.catch(handleErrors)
;

Axios, and promises in general are important pieces of software development today. When using the microservice architecture. Sending and receiving data is an essential function of each service. And Axios and promsies help developers do just that. Axios and promises work asynchronously meaning that they can run different parts of the program simultaneously. This is another important concept because sometimes differrent parts of a web page load asynchronously. So an asynchronous method could render the first available piece of data.