How to Use Axios in Node.js

Jan 13, 2021

When making http requests, users have the option of using fetch() from the vanilla javascript library to be used on the frontend, or from importing node-fetch. Another option available to those developers is the axios library. Instead of having to do:

const fetch = require('node-fetch');
return fetch(`API/make/request`, {
  method: "GET",
  headers:{
    Accept: 'define what to accept',
    Authorization: "authorization"
  },
}).then(response => {
  return response
}).catch(err => {
  console.log(err);
});

You can do the following:

const res = await axios.get('https://httpbin.org/get?answer=42',{
  headers:{
    Accept: 'accept',
    Authorization: 'authorize'
  },
}).then(response => {
  return response;
}).catch(err => {
  console.log(err);
});

Or for a simple POST request:

const res = await axios.post('https://httpbin.org/post', { hello: 'world' });

res.data.json; // { hello: 'world' }

When sending requests with data, the data can be of type:

Note: Stream and Buffer is for Node only while Form Data, File, and Blob is for the browser only.


Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Axios Tutorials