How to Use JSON with Axios

Apr 21, 2021

By default, when making a request to a server using axios, the Content-Type is set to send JSON data. The server is not held to that same standard however and may send the data back in a different format. Axios has the transformResponse to enable you to specify how you want it received on the response. Below is an example demonstrating how to make a simple GET request with Axios:

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

How to POST/PUT JSON

When making a POST or PUT request, Axios will automatically parse the data to JSON, provided you are sending an object, and make the necessary adjustments elsewhere in the request so it can be automatically parsed once received by the server.

POST

// Axios automatically serializes `{ answer: 42 }` into JSON.
const res = await axios.post('https://httpbin.org/post', { answer: 42 });

res.data.data; // '{"answer":42}'
res.data.headers['Content-Type']; // 'application/json;charset=utf-8',

PUT

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

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

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

More Axios Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!