Send a POST Request to Another Server in Node.js

04/10/2023
Contents
In this article, you will learn how to send a POST request to another server in Node.js.
Sending a POST request to another server
Sending a POST request to another server in Node.js involves making use of the built-in http or https module to send the request and receive a response. Here are the steps to do so:
Import the required modules
const https = require('https');
const querystring = require('querystring');
Create the data to be sent in the request
This can be done using the querystring module, which converts JavaScript objects into query strings.
const postData = querystring.stringify({
'username': 'example_user',
'password': 'example_password'
});
Define the options for the request
Define the options for the request, including the server URL, method, headers, and any other required options.
const options = {
hostname: 'example.com',
port: 443,
path: '/login',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};
Send the request using the https.request() method
const req = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`);
res.on('data', (d) => {
process.stdout.write(d);
});
});
Write the data to the request body and end the request
req.write(postData);
req.end();
Here’s the complete example:
const https = require('https');
const querystring = require('querystring');
const postData = querystring.stringify({
'username': 'example_user',
'password': 'example_password'
});
const options = {
hostname: 'example.com',
port: 443,
path: '/login',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};
const req = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`);
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.on('error', (error) => {
console.error(error);
});
req.write(postData);
req.end();
This example sends a POST request to https://example.com/login with the username and password parameters in the request body. The response is logged to the console.