Skip to content

Instantly share code, notes, and snippets.

@adinan-cenci
Last active April 29, 2019 23:31
Show Gist options
  • Save adinan-cenci/49cab92d53c1581ae238782e83094181 to your computer and use it in GitHub Desktop.
Save adinan-cenci/49cab92d53c1581ae238782e83094181 to your computer and use it in GitHub Desktop.
A simple way of making a GET request, details such as headers may be modified
const http = require('http');
const https = require('https');
const url = require('url');
async function request(address, options = {})
{
var myUrl = url.parse(address);
var protocol = myUrl.protocol == 'https:' ? https : http;
var defaultOptions =
{
hostname : myUrl.hostname,
port : myUrl.port,
path : myUrl.path,
agent : false // Create a new agent just for this one request
};
var options = {...defaultOptions, ...options};
return new Promise(async function(success, fail)
{
protocol.get(options, (res) =>
{
if (res.statusCode !== 200) {
fail('Error: ' + res.statusCode);
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', function(chunk)
{
rawData += chunk;
});
res.on('end', function()
{
success(rawData);
});
}).on('error', (e) => {
fail(e.message);
});
});
}
/*
// Example:
request('http://some-website.net/api?query=foo+bar').then(function(response)
{
console.log(response);
});
// custom headers:
request('http://some-website.net/api?query=foo+bar', {headers: {'user-agent': 'JustMyself/0.1.0 ( myself@gmail.com )'}})
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment