Skip to content

Instantly share code, notes, and snippets.

@hinchley
Created February 23, 2020 04:19
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 hinchley/6658fb58e968338bde364c95eeb3c82a to your computer and use it in GitHub Desktop.
Save hinchley/6658fb58e968338bde364c95eeb3c82a to your computer and use it in GitHub Desktop.
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