Last active
April 29, 2019 23:31
-
-
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
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 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 ( [email protected] )'}}) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment