Skip to main content

Node-Fetch: How to Send POST Requests

How to Send POST Requests With NodeJS Node-Fetch

To send POST requests with Node-Fetch call the fetch method with url as the first argument and options as the second argument. Inside options object, you need to add the POST bodystring and headers object. headers is where you define http headers like Content-Type.


import fetch from 'node-fetch';
const url = 'https://httpbin.org/post';
const options = {
method: 'POST',
body: { key: 'value' },
headers: {
'Content-Type': 'application/json'
}
};

fetch(url, options)
.then(response => {
return response.json()
})
.then(data => {
console.log(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 Node-Fetch.

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

Let's begin...


POST JSON Data Using NodeJS Node-Fetch

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

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


import fetch from 'node-fetch';
const url = 'https://httpbin.org/post';
const body = { key: 'value' }
const options = {
method: 'POST',
body: body,
headers: {
'Content-Type': 'application/json'
}
};

fetch(url, options)
.then(response => {
return response.json()
})
.then(data => {
console.log(data)
})
.catch(error => {
console.error(error);
});


POST Form Data Using NodeJS Node-Fetch

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

To make form data POST requests with Node-Fetch we simply need to add the data to the request using the body parameter of the POST request:


import fetch from 'node-fetch';
import querystring from 'querystring';
const url = 'https://httpbin.org/post'
const data = { key: 'value' }
const options = {
method: 'POST',
body: querystring.stringify(data),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};

fetch(url, options)
.then(response => {
return response.json()
})
.then(data => {
console.log(data)
})
.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. Also note that we have set body to a string representation of data calculated using querystring.stringify function.


More Web Scraping Tutorials

So that's how you can send POST requests using NodeJs Node-Fetch.

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: