swislokdev

Swislok-Dev

Posted on May 2, 2022

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.

💖 💪 🙅 🚩
swislokdev
Swislok-Dev

Posted on May 2, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Axios some info
javascript Axios some info

May 2, 2022