javascript

​​How to make a POST JSON request with Axios


In this article, you will learn about Post JSON request with Axios.

In JavaScript, Axios is a library that is used to make HTTP requests from Node and is also used in front-end applications. It is a promise-based API.

You can Post JSON requests with Axios by calling axios.post() method. This method simply expects two parameters. The first one is URI and the second one is Object that contains the properties. In the second parameter, if you pass the JavaScript object, Axios will automatically serialize it into JSON for you and it will also set the Content-Type header to application/json. See the code example below:

const res = await axios.post('<https://test.org/post>', { name: 'deven' });

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

Now, what if you want to send a serialized JSON string as the second parameter of axios.post() method. Axios will simply treat it as a form-encoded request body instead of setting the content-type header to application/json. See the issue in the below:

const json = JSON.stringify({ name: 'deven' });
const res = await axios.post('<https://test.org/post>', json);

res.data.headers['Content-Type']; // 'application/x-www-form-urlencoded',

To avoid this unwanted situation you can simply set the content-type header explicitly and you may get your desired solution. For example:

const json = JSON.stringify({ name: 'deven' });
const res = await axios.post('<https://test.org/post>', json, {
  headers: {
    'Content-Type': 'application/json'
  }
});

res.data.data; // '{"name":"deven"}'
res.data.headers['Content-Type']; // 'application/json',

Share on social media

//