Created
August 6, 2020 16:19
-
-
Save JosePedroDias/f8c348c683185d67bbf2194185b9e1c1 to your computer and use it in GitHub Desktop.
to eventually use in node instead of request
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'); | |
const https = require('https'); | |
const HEADERS = {}; | |
function get(url, body, moreHeaders) { | |
const prot = url.indexOf('https:') === 0 ? https : http; | |
return new Promise((resolve, reject) => { | |
const r = prot.request( | |
url, | |
{ | |
method: body ? 'POST' : 'GET', | |
headers: { | |
...HEADERS, | |
...(moreHeaders && moreHeaders), | |
}, | |
}, | |
(resp) => { | |
let data = ''; | |
resp.on('data', (chunk) => { | |
data += chunk; | |
}); | |
resp.on('end', () => { | |
try { | |
resolve(JSON.parse(data)); | |
} catch (_) { | |
resolve(data); | |
} | |
}); | |
resp.on('error', reject); | |
} | |
); | |
if (body) { | |
r.write(body); | |
} | |
r.end(); | |
}); | |
} | |
module.exports = { get }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment