POST JSON with Axios
Jun 12, 2020
If you pass a JavaScript object as the 2nd parameter to the axios.post()
function, Axios will automatically serialize the object to JSON
for you. Axios will also set the Content-Type
header to 'application/json'
,
so web frameworks like Express can automatically parse it.
// 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',
This means you normally don't have to worry about serializing POST bodies to JSON: Axios handles it for you.
With Pre-Serialized JSON
If you happen to have a serialized JSON string that you want to
send as JSON, be careful. If you pass a string to axios.post()
, Axios
treats that as a form-encoded request body.
const json = JSON.stringify({ answer: 42 });
const res = await axios.post('https://httpbin.org/post', json);
// Axios automatically sets the `Content-Type` based on the
// 2nd parameter to `axios.post()`.
res.data.headers['Content-Type']; // 'application/x-www-form-urlencoded',
The solution is easy: make sure you set the Content-Type
header if
you pass a pre-serialized JSON string to axios.post()
.
const json = JSON.stringify({ answer: 42 });
const res = await axios.post('https://httpbin.org/post', json, {
headers: {
// Overwrite Axios's automatically set Content-Type
'Content-Type': 'application/json'
}
});
res.data.data; // '{"answer":42}'
res.data.headers['Content-Type']; // 'application/json',
Did you find this tutorial useful? Say thanks by starring our repo on GitHub!