POST JSON with Axios

Jun 12, 2020

If you pass a JavaScript object as the 2nd parameter to the 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'', { answer: 42 });; // '{"answer":42}'['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 treats that as a form-encoded request body.

const json = JSON.stringify({ answer: 42 });
const res = await'', json);

// Axios automatically sets the `Content-Type` based on the
// 2nd parameter to ``.['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

const json = JSON.stringify({ answer: 42 });
const res = await'', json, {
  headers: {
    // Overwrite Axios's automatically set Content-Type
    'Content-Type': 'application/json'
});; // '{"answer":42}'['Content-Type']; // 'application/json',

More Axios Tutorials