Skip to main content

NodeJs Request-Promise: How to Send POST Requests

NodeJs Request Promise: How to Send POST Requests

How to Send POST Requests With NodeJS Request Promise

To send POST requests with NodeJS Request Promise use the request method and add the POST body and Content-Type using the body and headers parameters.


const request = require('request-promise');

const options = {
method: 'POST',
uri: 'https://httpbin.org/post',
body: { key: 'value' },
json: true,
headers: {
'Content-Type': 'application/json'
}
};

request(options)
.then(response => {
console.log(response);
})
.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 Request Promise.

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

Let's begin...

Need help scraping the web?

Then check out ScrapeOps, the complete toolkit for web scraping.


POST JSON Data Using NodeJS Request Promise

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

We simply just need to add the data to the request using the body parameter within our request options:


const request = require('request-promise');

const options = {
method: 'POST',
uri: 'https://httpbin.org/post',
body: { key: 'value' },
json: true,
headers: {
'Content-Type': 'application/json'
}
};

request(options)
.then(response => {
console.log(response);
})
.catch(error => {
console.error(error);
});


POST Form Data Using NodeJS Request Promise

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

To make form data POST requests with Request-Promise we simply need to add the data to the request using the data parameter of the POST request:


const request = require('request-promise');

const options = {
method: 'POST',
uri: 'https://httpbin.org/post',
body: { key: 'value' },
json: true,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};

request(options)
.then(response => {
console.log(response);
})
.catch(error => {
console.error(error);
});

Here we set the Content-Type header 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 Request Promise.

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: