Skip to content

Instantly share code, notes, and snippets.

@abhinavKeshri07
Created November 25, 2019 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhinavKeshri07/a009dee467882ea8879af89e8d669aff to your computer and use it in GitHub Desktop.
Save abhinavKeshri07/a009dee467882ea8879af89e8d669aff to your computer and use it in GitHub Desktop.
This file lets you make post request to any server running https or http with nodejs. You can modify the code send json data. Thank me later.
const https = require('https');
const http = require('http');
const querystring = require('querystring');
const url = require('url');
let get_POST_data = function(urlToPost, formData, headersToSend) {
return new Promise(function(resolve, reject) {
let parsed_url = url.parse(urlToPost);
let post_data = querystring.stringify(formData);
let secure = false;
if (parsed_url.protocol === 'https:') {
secure = true;
}
headersToSend["Content-Length"] = post_data.length;
headersToSend["Host"] = parsed_url.hostname;
headersToSend["Origin"] = parsed_url.protocol + '//' + parsed_url.hostname;
headersToSend["Referer"] = parsed_url.protocol + '//' + parsed_url.hostname;
let options = {
host: parsed_url.hostname,
port: parsed_url.port,
path: parsed_url.path,
method: 'POST',
headers: headersToSend
}
let protocol = http;
if (secure) {
options.rejectUnauthorized = false;
protocol = https;
}
let cbresponse = "";
let request = protocol.request(options, (response) => {
response.setEncoding('utf8');
response.on('data', function(chunk) {
cbresponse = cbresponse + chunk;
});
});
request.on('error', (e) => {
reject(e);
});
request.on('close', () => {
resolve(cbresponse);
});
request.write(post_data);
request.end();
});
}
module.exports = get_POST_data;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment