In this tutorial we will discuss about making HTTP POST requests from Node. This is similar to sending cURL request from PHP.
http / https Module
To enable transfer of data over HTTP, Node provides the http module. This module holds the APIs to stream HTTP requests and responses.
The http module is built-in to Node. You don't need to install it separately.
To use this module, it is first required to be imported :
const http = require('http');
NOTE : To make HTTPS requests you will need to import the https module.
const https = require('https');
Using the https module is the same as using the http module. Both have the same APIs. In the rest of the tutorial we will send a HTTP request, but the same methods apply for sending a HTTPS request also — simply replace http by https.
Creating Payload for the POST Request
A POST request includes a payload data that is sent to the server as a query string (key-value pairs separated by a & character).
A query string can be formed from the POST parameters using the inbuilt querystring module.
const querystring = require('querystring');
const parameters = {
name: "UsefulAngle",
type: "Website"
}
// parameters as query string
// ?name=UsefulAngle&type=Website
const post_data = querystring.stringify(parameters);
Sending POST Request
A POST request can be sent using the request method of the imported http object. This method accepts an object parameter in which you can set the options for the POST request.
const http = require('http');
const querystring = require('querystring');
// POST parameters
const parameters = {
name: "UsefulAngle",
type: "Website"
}
// POST parameters as query string
const post_data = querystring.stringify(parameters);
const options = {
url: "http://www.usefulangle.com",
port: "80",
path: "/post/ajax.php",
method: "POST"
}
const request = http.request(options, (response) => {
// response from server
});
request.write(post_data);
request.end();
Setting Request HTTP Headers
The request headers can be set by creating a headers object in the options for the POST request. The request header data goes in key-value pairs.
After adding the request header, the option for the request looks something like :
const options = {
url: "http://www.usefulangle.com",
port: "80",
path: "/post/ajax.php",
method: "POST",
headers : {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
Handling Errors while Sending Request
An error event is emitted when an error is encountered while sending the request. To handle the error a listener is attached to the event. This listener accepts an object of Error class as a parameter.
The error code and message is retrieved as shown:
request.on('error', (error) => {
console.log('Error Code: ' + error.code);
console.log('Error Message: ' + error.message);
});
Getting Response from Server
Response from the sever is gathered through a callback passed in the http.request method.
const request = http.request(options, (response) => {
// response from server
});
Node accepts the response from the server as a stream — response data comes in as a series of incoming chunks. If the response from server is small, there may be only a single chunk returned. If the response is huge, numerous chunks keep on arriving.
In code we must gather all these chunks and combine them into a single response data at the end. We gather these chunks through events.
The response object emits a data event when a chunk arrives and a end event when all chunks have arrived.
const request = http.request(options, (response)=>{
// holds all chunks
let chunks_of_data = [];
// gather chunk
response.on('data', (fragments) => {
chunks_of_data.push(fragments);
});
// no more data to come
// combine all chunks
response.on('end', () => {
let response_body = Buffer.concat(chunks_of_data);
// response body as string
console.log(response_body.toString());
});
});
Getting Response Headers
The response headers can be obtained from the headers property of the response object. The response headers are in key-value pairs.
const request = http.request(options, (response) => {
// response headers
console.log(response.headers);
});
Getting HTTP Response Code
The response code (200, 404, 500 etc) is obtained from the statusCode property of the response object.
const request = http.request(options, (response) => {
// HTTP status code
console.log(response.statusCode);
});
Handling Errors while Receiving Response
The response objects emits an error event in case an error is thrown during the process of getting the response.
response.on('error', (error) => {
console.log('Error Code: ' + error.code);
console.log('Error Message: ' + error.message);
});
Complete Code
const http = require('http');
const querystring = require('querystring');
const parameters = {
name: "UsefulAngle",
type: "Website"
}
const post_data = querystring.stringify(parameters);
const options = {
url: "http://www.usefulangle.com",
port: "80",
path: "/post/ajax.php",
method: "POST",
headers : {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
const request = http.request(options, (response)=>{
let chunks_of_data = [];
response.on('data', (fragments) => {
chunks_of_data.push(fragments);
});
response.on('end', () => {
let response_body = Buffer.concat(chunks_of_data);
console.log(response_body.toString());
});
response.on('error', (error) => {
console.log(error);
});
});
request.on('error', (error) => {
console.log('Error Code: ' + error.code);
console.log('Error Message: ' + error.message);
});
request.write(post_data);
request.end();