Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save guerrerocarlos/9bf7c139fbb657a8befcb98b2fb0d478 to your computer and use it in GitHub Desktop.
Save guerrerocarlos/9bf7c139fbb657a8befcb98b2fb0d478 to your computer and use it in GitHub Desktop.
Node.js making a HTTPS request with GET and POST
const https = require('https');
async function httpsGet(hostname, path, headers) {
return new Promise(async (resolve, reject) => {
const options = {
hostname: hostname,
path: path,
port: 443,
method: 'GET',
headers: headers
};
let body = [];
const req = https.request(options, res => {
res.on('data', chunk => body.push(chunk));
res.on('end', () => {
const data = Buffer.concat(body).toString();
resolve(data);
});
});
req.on('error', e => {
// console.log(`ERROR httpsGet: ${e}`);
reject(e);
});
req.end();
});
}
async function httpsPost(hostname, path, data) {
return new Promise(async (resolve, reject) => {
const options = {
hostname: hostname,
path: path,
port: 443,
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
};
const body = [];
const req = https.request(options, res => {
// console.log('httpsPost statusCode:', res.statusCode);
// console.log('httpsPost headers:', res.headers);
res.on('data', d=> {
body.push(d);
});
res.on('end', () => {
// console.log(`httpsPost data: ${body}`);
// resolve(JSON.parse(Buffer.concat(body).toString()));
resolve("{'name': 'jason'}");
});
});
req.on('error', e => {
// console.log(`ERROR httpsPost: ${e}`);
reject(e);
});
req.write(JSON.stringify(data));
req.end();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment