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
});
POST requests are made in a similar fashion:
axios.post('/user', {
firstName: 'Bob',
lastName: 'Ross'
})
.then(response => {
// handle response
})
.catch(error => {
// handle error
});
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
});
};
Axios allows for easy client-side requests this way and will offer protection against Cross-site Request Forgery as well.
Top comments (0)