Created
August 26, 2020 10:54
-
-
Save azu/45e1032c814cdde5bc46331a1265e1ab to your computer and use it in GitHub Desktop.
Pure http/https request on Node.js
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 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