Skip to content

Instantly share code, notes, and snippets.

@gracefullight
Created February 20, 2017 08:22
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 gracefullight/4f40dfc7fd8493b6fc40471e220305d5 to your computer and use it in GitHub Desktop.
Save gracefullight/4f40dfc7fd8493b6fc40471e220305d5 to your computer and use it in GitHub Desktop.
function httpRequest(params, postData) {
return new Promise(function(resolve, reject) {
var req = http.request(params, function(res) {
// reject on bad status
if (res.statusCode < 200 || res.statusCode >= 300) {
return reject(new Error('statusCode=' + res.statusCode));
}
// cumulate data
var body = [];
res.on('data', function(chunk) {
body.push(chunk);
});
// resolve on end
res.on('end', function() {
try {
body = JSON.parse(Buffer.concat(body).toString());
} catch(e) {
reject(e);
}
resolve(body);
});
});
// reject on request error
req.on('error', function(err) {
// This is not a "Second reject", just a different sort of failure
reject(err);
});
if (postData) {
req.write(postData);
}
// IMPORTANT
req.end();
});
}
var params = {
host: '127.0.0.1',
port: 4000,
method: 'GET',
path: '/api/v1/service'
};
httpRequest(params).then(function(body) {
console.log(body);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment