Skip to main content

NodeJs Axios: Make POST  Requests

NodeJs Axios: How to Send POST Requests

How to Send POST Requests With NodeJS Axios

To send POST requests with NodeJS Axios call the axios.post method with uri as the first argument and POST body as the second argument. The third argument is the options object and here you can set Content-Type using the headers parameter.


const axios = require('axios');

const uri = 'https://httpbin.org/post'
const data = { key: 'value' }
const options = {
headers: {
'Content-Type': 'application/json'
}
}

axios.post(uri, data, options)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});

In this guide for The NodeJs Web Scraping Playbook, we will look at how to make POST requests with the NodeJS Axios.

In this guide we will walk you through the most common ways of sending POST requests with NodeJS Axios:

Let's begin...

If you prefer to follow along with a video then check out the video tutorial version here:


POST JSON Data Using NodeJS Axios

A common scenario for using POST requests is to send JSON data to an API endpoint, etc. Making POST requests this with NodeJS Axios is very simple.

We simply just need to call axios.post method with data as the second argument:


const axios = require('axios');

const uri = 'https://httpbin.org/post'
const data = { key: 'value' }
const options = {
headers: {
'Content-Type': 'application/json'
}
}

axios.post(uri, data, options)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});


POST Form Data Using NodeJS Axios

Another common use case for using POST requests is to send form data to an endpoint.

To make form data POST requests with Axios we simply need to call axios.post method with form data as the second argument.

const axios = require('axios');

const uri = 'https://httpbin.org/post'
const data = `key1=value1&key2=value2`
const options = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}

axios.post(uri, data, options)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});

Here Content-Type header in the third options argument is set to application/x-www-form-urlencoded so that the body will be picked up as form data.


More Web Scraping Tutorials

So that's how you can send POST requests using NodeJs Axios.

If you would like to learn more about Web Scraping, then be sure to check out The Web Scraping Playbook.

Or check out one of our more in-depth guides: