Skip to content

Instantly share code, notes, and snippets.

@UmeshSingla
Last active April 3, 2023 15:53
Show Gist options
  • Save UmeshSingla/d5088268df51dacd6fa6 to your computer and use it in GitHub Desktop.
Save UmeshSingla/d5088268df51dacd6fa6 to your computer and use it in GitHub Desktop.
http, https post request in node.js
//Install required modules, and include them
var https = require('https'), // https server
http = require('http'), // http server
querystring = require('querystring'),
url = require('url'); // url parser
//URL to which post request will be sent
var callback_url = 'http://example.com';
var callback = url.parse(callback_url);
//Define user agent for your node
var api_agent = 'My node Server';
//Post data
var text = {};
text.success = true;
text.data = {};
text.data.site_name = 'example.com';
//Actul data sent, which needs to be decoded on serve side
var out_text = querystring.escape(JSON.stringify(output));
var secure = false;
if (callback.protocol === 'https:') {
secure = true;
}
var options = {
host: callback.hostname,
port: callback.port,
path: callback.path,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': out_text.length,
'User-Agent': api_agent,
'Referer': callback.protocol + '//' + callback.hostname
}
};
var protocol = http;
if (secure) {
options.rejectUnauthorized = false;
protocol = https;
}
var request = protocol.request(options, function (response) {
response.setEncoding('utf8');
response.on('data', function (cbresponse) {
console.log(cbresponse);
});
});
request.on('error', function (e) {
console.log('problem with request: ');
console.log(e);
});
//write data to server
request.write(out_text);
request.end();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment