Created
December 21, 2022 13:58
-
-
Save crlspe/3f61400ac9af80039ede3d502aebbfdf to your computer and use it in GitHub Desktop.
Makes Http GET and POST requests
This file contains 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 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