Request is designed to be the simplest way possible to make http calls. It supports HTTPS and follows redirects by default.
Request is very useful in cases of API interactions and web scraping.
To install the request module, simply run the following command
sudo npm install -g request
In project directory link installed modules to local dir
npm link request
Simple GET call over HTTP (coffescript)
request = require('request') request('http://en.proft.me', (error, response, body) -> if !error and response.statusCode == 200 console.log(body) )
By default the request module makes a GET request, if not specified explicitly.
Body is a string type containing the contents of the body if the response is in text format, the body is a buffer if the response data is in the binary/octet stream encoding, finally the body will be a JSON object if the response is in JSON encoding.
GET call with parameters
request = require('request') headers = 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64)', options = url: 'http://url.com', method: 'GET', headers: headers, qs: {'key1': 'value1', 'key2': 'value2'} request(options, (error, response, body) -> if !error and response.statusCode == 200 console.log(body) )
POSTing form
request = require('request') headers = 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64)', options = url: 'http://url.com', method: 'POST', headers: headers, form: {'key1': 'value1', 'key2': 'value2'} request(options, (error, response, body) -> if !error and response.statusCode == 200 console.log(body) )
or
request.post('http://url.com').form({key1:'value1'})
POSTing JSON object
request = require('request'); headers = 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64)', options = url: 'http://url.com', method: 'POST', headers: headers, json: {'key1': 'value1', 'key2': 'value2'} request(options, (error, response, body) -> if !error and response.statusCode == 200 console.log(body) )
Downloading remote file
request = require('request') fs = require('fs') out = fs.createWriteStream('/tmp/image.png'); request('http://url.com/static/image.png') .on('error', (error) -> console.log(error) ) .pipe(out)
Sending file via POST request
request = require('request') fs = require('fs') source = fs.createReadStream('/tmp/movie.json') source.pipe(request.post('http://url.com/form'))
As always, you have an alternative - needle.