Last active
October 26, 2023 18:55
-
-
Save rajinder-yadav/c7e7fbd1ce6d90793c73c4bf1872e4a9 to your computer and use it in GitHub Desktop.
Node.js making a HTTPS request with GET and POST
This file contains hidden or 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
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
https.request()
is not an async function so theawait
keyword before the function call is not valid.