Skip to content

Instantly share code, notes, and snippets.

@sundeepgupta
Created August 11, 2016 14:27
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 sundeepgupta/579bcd4f4701dd2e98b8b7def43bc50d to your computer and use it in GitHub Desktop.
Save sundeepgupta/579bcd4f4701dd2e98b8b7def43bc50d to your computer and use it in GitHub Desktop.
node.js http module
'use strict';
const HTTPS = require('https');
const URL = require('url');
const QueryString = require('querystring');
module.exports = function() {
return {
postJSON: function(url, params) {
const data = JSON.stringify(params);
const contentType = 'application/json'
return post(url, data, contentType);
},
postForm: function(url, params) {
const data = QueryString.stringify(params);
const contentType = 'application/x-www-form-urlencoded'
return post(url, data, contentType);
}
};
function post(url, data, contentType) {
return new Promise(function(resolve, reject) {
const urlObject = URL.parse(url);
const options = {
port: 443,
hostname: urlObject.hostname,
path: urlObject.path,
method: 'POST',
headers: {'Content-Type': contentType}
}
const request = HTTPS.request(options, function(response) {
console.log('Response status: ' + response.statusCode);
var data = '';
response.on('data', function(chunk) {
data += chunk;
});
response.on('end', () => {
console.log('Data: ' + data);
resolve(data.toString());
});
});
request.on('error', function(error) {
console.log('error: ' + JSON.stringify(error));
reject(error);
});
console.log('\n\nOutgoing POST request to ' + url + ' with data: ' + data);
request.end(data);
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment