Created
February 20, 2017 08:22
-
-
Save gracefullight/4f40dfc7fd8493b6fc40471e220305d5 to your computer and use it in GitHub Desktop.
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
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