Skip to content

Instantly share code, notes, and snippets.

@vaz
Last active June 6, 2017 02:11
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 vaz/c44f6dc47983efe73b1622c33619c8d5 to your computer and use it in GitHub Desktop.
Save vaz/c44f6dc47983efe73b1622c33619c8d5 to your computer and use it in GitHub Desktop.
request examples
var request = require('request');
var url = 'http://www.google.com';
// basic use
request.get(url, function(err, response, body) {
if (err) {
console.log("Error:", err);
} else {
// response.body == body
console.log("Body:", body);
}
});
var request = require('request');
// build the request URL
var requestURL = 'https://' + 'www.google.com';
// specifying other request properties, like headers
var requestOptions = {
url: requestURL,
headers: {
'User-Agent': "this can be anything"
}
};
request.get(requestOptions, function(err, response, body) {
if (err) {
console.log("Error:", err);
} else {
// response.body == body
console.log("Body:", body);
}
});
var request = require('request');
// build the request URL
var requestURL = 'https://' + 'www.google.com';
// specifying other request properties, like headers
var requestOptions = {
url: requestURL,
headers: {
'User-Agent': "this can be anything"
}
};
request.get(requestOptions, function(err, response, body) {
if (err) {
console.log("Error:", err);
} else {
// the body is read here
// response.body == body
// console.log("Body:", body);
}
})
.on('error', function(err) {
throw err;
})
.on('response', function(response) {
console.log('status code:', response.statusCode);
// the body is not yet read (response.body is undefined)
console.log('response body:', response.body)
});
// chaining async functions with callbacks
function getRepoContributors(owner, name, cb) {
var url = '...';
request.get(url, function(err, response, body) {
if (err) {
cb(err);
} else {
cb(null, body)
}
});
}
getRepoContributors('jquery', 'jquery', function(err, contributors) {
if (err) {
// handle it...
} else {
// I have an array of contributors
doSomethingElseAsync(function(err, result) {
// ...
})
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment