Skip to content

Instantly share code, notes, and snippets.

@crlspe
Created December 21, 2022 13:58
Show Gist options
  • Save crlspe/3f61400ac9af80039ede3d502aebbfdf to your computer and use it in GitHub Desktop.
Save crlspe/3f61400ac9af80039ede3d502aebbfdf to your computer and use it in GitHub Desktop.
Makes Http GET and POST requests
const http = require('http');
function get(url) {
return new Promise((resolve, reject) => {
http.get(url, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
resolve(data);
});
}).on('error', (err) => {
reject(err);
});
});
}
function post(endpoint, data) {
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
};
const url = new URL(endpoint);
options.hostname = url.hostname;
options.path = url.pathname;
return new Promise((resolve, reject) => {
const req = http.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
resolve(data);
});
});
req.on('error', (err) => {
reject(err);
});
req.write(data);
req.end();
});
}
module.exports = {
get,
post,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment