Axios for Node.js
Axios is a promise based HTTP client for browser and node.js; it can be used on server side and client side (Browser) to interact with API (Application Programming Interface to send request from the browser and node.js server to other API and get a response).
On client side(Browser) Axios uses XMLHttpRequests and On server-side it uses http module
$ npm install axios
const axios = require(‘axios’);
let userID = ‘123456’;
axios.get(`/userInfo?id=${userID}`).
then(response=>{
console.log(response)
}).catch(error=>{
console.log(error)
});
async function getUserInfo(){
try{
let userInfo = await axios.get(````/userInfo?id=${userID}`);
}catch(error){
console.log(error)
}
}
axios.post('/userInfo', {
firstName: 'FName',
lastName: 'LName',
dob: ‘06/15/2001’
}).then(response=> {
console.log(response);
}).catch(error=> {
console.log(error);
});
axios.delete(‘/userInfo/’+{userID}).then(response=>{
console.log(response);
}).catch(error=>{
console.log(error);
});
axios({
method: 'get',
url: 'https://images.app.goo.gl/3g4ez2auLnyoYG1u8',
responseType: 'stream'
}).then(response=> {
response.data.pipe(fs.createWriteStream('forest.jpg'))
}).catch(error=>{
console.log(error)
});
To send file with Axios in node.js
let url = `API_URL` //API URl where you post filelet fileRecievedFromClientSide = req.file;
let buffer = fs.readFileSync(fileRecievedFromClientSide.path);
let form = new FormData();
form.append('xlsx', buffer, fileRecievedFromClientSide.originalname);
Axios.post(url, form, {
'maxContentLength': Infinity,
'maxBodyLength': Infinity,
headers: {
'Content-Type': `multipart/form-data,
boundary=${form._boundary}`,
}
}).then(response => {
console.log(response)
}).catch(error => {
console.log(error)
});
Hope you would love this summary!