Skip to main content

NodeJS Got: How to Send POST Requests

How to Send POST Requests With NodeJS Got

To send POST requests with Got, simply call the got.post method with url as the first argument and request options as the second argument. Inside options object, you need to add the POST body string and headers object. headers is where you define http headers like Content-Type.

import got from 'got';

const url = 'https://httpbin.org/post';
const options= {
body: 'Hello world!',
headers: {
'Content-Type': 'text/plain'
}
};
got.post(url, options)
.then(response => {
console.log(response.body);
})
.catch(error => {
console.log(error);
})

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

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

Let's begin...


POST JSON Data Using NodeJS Got

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

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


import got from 'got';
const url = 'https://httpbin.org/post';
const data = { key: 'value' };
const options = {
json: data
};

got.post(url, options)
.then(response => {
console.log(response.body);
})
.catch(error => {
console.error(error);
});

Here Content-Type header gets automatically set to application/json. And data object is converted into json string before it is sent as POST body.


POST Form Data Using NodeJS Got

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

To make form data POST requests with Got we simply need to add the data to the request using the form parameter of the request options:


import got from 'got';
const url = 'https://httpbin.org/post';
const data = { key: 'value' };
const options = {
form: data
};

got.post(url, options)
.then(response => {
console.log(response.body);
})
.catch(error => {
console.error(error);
});

Here got automatically sets Content-Type header to application/x-www-form-urlencoded so that the POST body will be picked up as form data. Also data object is converted into query string representation, key=value, before it is sent as POST body.


More Web Scraping Tutorials

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

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: