Skip to content

Instantly share code, notes, and snippets.

@hinchley
Created Feb 23, 2020
Embed
What would you like to do?
HTTP requests in Node.js
const fetch = (url, cb, options = {}) => {
const { protocol } = new URL(url);
const http = protocol === 'https:'
? require('https')
: require('http');
options = { headers: { 'User-Agent': 'node.js' }, ...options };
const error = e => console.log(e.message);
http.get(url, options, res => {
const chunks = [];
res.on('data', chunk => chunks.push(chunk));
res.on('end', () => {
const data = chunks.join('')
try { cb(JSON.parse(data)); }
catch (e) { cb(data); }
});
}).on('error', error);
};
const fetchp = async (url, options) => {
return new Promise((resolve, reject) => {
fetch(url, json => resolve(json), options);
});
};
// callback syntax:
fetch('https://api.github.com/users/hinchley', data => console.log(data));
// http request:
fetch('http://taco-randomizer.herokuapp.com/random/', data => console.log(data));
// non-json response:
fetch('https://google.com', data => console.log(data));
// invalid request:
fetch('https://invalid....com', data => console.log(data));
// promisified version:
(async () => {
const data = await fetchp('https://api.github.com/users/hinchley');
console.log(data);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment