Skip to content

Instantly share code, notes, and snippets.

@rajinder-yadav
Last active October 26, 2023 18:55
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rajinder-yadav/c7e7fbd1ce6d90793c73c4bf1872e4a9 to your computer and use it in GitHub Desktop.
Save rajinder-yadav/c7e7fbd1ce6d90793c73c4bf1872e4a9 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();
});
}
@robertpatrick
Copy link

https.request() is not an async function so the await keyword before the function call is not valid.

@rajinder-yadav
Copy link
Author

Thanks for catching that @robertpatrick!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment