DEV Community

Swislok-Dev
Swislok-Dev

Posted on

4 3

Axios some info

What is axios?

Axios is a promise base HTTP client for node.js. On the server it uses the native node http module while on the client side it uses XMLHttpRequest system.

Using whatever package manager you like add axios to your list of dependencies and install.

To make a GET request some boilerplate is required in the file the request is made.

const axios = require('axios');

axios.get('/user', {
  params: {
    id: 1,
  }
})
  .then(response => {
 console.log(response);
  // do more with response
});
.catch(error => {
  console.error(error);
  // handle error
});
Enter fullscreen mode Exit fullscreen mode

POST requests are made in a similar fashion:

axios.post('/user', {
  firstName: 'Bob',
  lastName: 'Ross'
})
.then(response => {
  // handle response
})
.catch(error => {
  // handle error
});
Enter fullscreen mode Exit fullscreen mode

It is possible to use a single boilerplate for both GET and POST requests within a single function:

const request = (var) => {
  const options = {
    method: "VERB",
    url: "API-ENDPOINT",
    params: { `${var}` },
    headers: {
      "API-HOST": "HOST-NAME",
      "API-KEY": "KEY-VALUE",
    },
  },

  axios.request(options)
  .then(response => {
    // handle response
  })
  .catch(error => {
    // handle error
  });
};
Enter fullscreen mode Exit fullscreen mode

Axios allows for easy client-side requests this way and will offer protection against Cross-site Request Forgery as well.

Top comments (0)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!