Skip to content

Instantly share code, notes, and snippets.

@azu
Created August 26, 2020 10:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save azu/45e1032c814cdde5bc46331a1265e1ab to your computer and use it in GitHub Desktop.
Save azu/45e1032c814cdde5bc46331a1265e1ab to your computer and use it in GitHub Desktop.
Pure http/https request on Node.js
const http = require("http");
const https = require("https");
const fetch = (url, headers) => {
const urlObject = new URL(url);
const options = {
hostname: urlObject.hostname,
path: urlObject.pathname + urlObject.search,
method: 'GET',
headers: headers
};
return new Promise((resolve, reject) => {
(urlObject.protocol === "http:" ? http : https).request(options, (response) => {
let data = '';
response.setEncoding('utf8');
response.on('data', (chunk) => {
data += chunk
});
response.on('end', () => {
resolve(data);
});
}).on("error", (error) => {
reject(error);
}).end();
});
}
(async function () {
const res = await fetch("https://example.metadata", {
'Metadata-Flavor': 'Google',
});
console.log(res);
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment