Skip to content

Instantly share code, notes, and snippets.

@carloscarucce
Last active April 14, 2020 14:01
Show Gist options
  • Save carloscarucce/8e9c421de39bb0043de12871aa00674e to your computer and use it in GitHub Desktop.
Save carloscarucce/8e9c421de39bb0043de12871aa00674e to your computer and use it in GitHub Desktop.
Node https request example
const https = require('https');
/**
* Make a request
* @param {Object} options
* @param {Object|string} data
*/
const requestSSL = (options, requestData = null) => new Promise((resolve, reject) => {
// eslint-disable-next-line consistent-return
const req = https.request(options, (res) => {
const { statusCode } = res;
let error;
console.log(options)
if (statusCode >= 400) {
error = new Error(`Status Code: ${statusCode}`);
}
if (error) {
res.resume();
return reject(error);
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => {
rawData += chunk;
});
res.on('end', () => {
resolve({ response: rawData, statusCode });
});
});
req.on('error', (e) => {
const error = new Error(`Request failed: ${e.message}`);
reject(error);
});
// Checks if the request sent a data
if (requestData) {
req.write(requestData);
}
req.end();
});
//Run
let data = JSON.stringify({
"name": "Carlos"
});
let options = {
hostname: '127.0.0.1',
port: 443,
path: '/',
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
rejectUnauthorized: false //kinda bad idea but useful in some cases
};
let result = await requestSSL(options, data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment