Created
August 11, 2016 14:27
-
-
Save sundeepgupta/579bcd4f4701dd2e98b8b7def43bc50d to your computer and use it in GitHub Desktop.
node.js http module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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