DEV Community 👩‍💻👨‍💻

Swislok-Dev
Swislok-Dev

Posted on

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)

In defense of the modern web

I expect I'll annoy everyone with this post: the anti-JavaScript crusaders, justly aghast at how much of the stuff we slather onto modern websites; the people arguing the web is a broken platform for interactive applications anyway and we should start over;

React users; the old guard with their artisanal JS and hand authored HTML; and Tom MacWright, someone I've admired from afar since I first became aware of his work on Mapbox many years ago. But I guess that's the price of having opinions.