Get the HTTP Response Body with Axios

Jul 23, 2020

When you await on an Axios request, you get back an Axios response. An Axios response is a POJO with several properties, including data, which contains the parsed response body.

const axios = require('axios');

const res = await axios.get('https://httpbin.org/get', { params: { answer: 42 } });

res.constructor.name; // 'Object', means `res` is a POJO

// `res.data` contains the parsed response body
res.data; // { args: { answer: 42 }, ... }
res.data instanceof Object; // true

An Axios response contains several other properties, like status, which contains the HTTP response status code (like 200 or 404). But most of the time you don't care about the response code if the request succeeded, so you will often see code that gets the response body directly using promise chaining.

const data = await axios.get(url).then(res => res.data);

You can also get the response body using destructuring assignments.

// Equivalent to `const data = await axios.get(url).then(res => res.data)`
const { data } = await axios.get(url);

Automatic Parsing

Axios parses the response based on the HTTP response's Content-Type header. When the response's content type is application/json, Axios will automatically try to parse the response into a JavaScript object.

const axios = require('axios');

const res = await axios.get('https://httpbin.org/get', { params: { answer: 42 } });

res.headers['content-type']; // 'application/json'

Keep in mind that the response headers are sent by the server. So if the server sends back a different content type, you may need to handle it the response yourself.

For other content types, like text/html, the res.data property will be a string.

const axios = require('axios');

const res = await axios.get('https://httpbin.org/html');

res.headers['content-type']; // 'text/html; charset=utf-8'

typeof res.data; // 'string'
res.data; // '... <h1>Herman Melville - Moby-Dick</h1> ...'

Streaming

You can configure the type of the data property using Axios' responseType object. By default, responseType is set to 'json', which means Axios will try to parse the response as JSON.

However, that isn't correct if you're looking to, say, download an image using Axios. You can set responseType to 'arraybuffer' to get the response as an ArrayBuffer:

const axios = require('axios');

const res = await axios.get('https://images.unsplash.com/photo-1506812574058-fc75fa93fead', {
  responseType: 'arraybuffer'
});

const fs = require('fs');
fs.writeFileSync('./south-beach.jpg', res.data);

You can also set responseType to 'stream' to get the response as a Node.js stream:

const axios = require('axios');

const res = await axios.get('https://images.unsplash.com/photo-1506812574058-fc75fa93fead', {
  responseType: 'stream'
});

const fs = require('fs');
res.data.pipe(fs.createWriteStream('./south-beach.jpg'));

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