If you don’t know how to setup node.js libraries, read this.
This tutorial will provide sample codes for:
setting the HTTP headers,
setting the URL query string for GET
setting the HTTP body for POST
handling gzip response
handling json response
GET
1234567891011121314151617181920212223
varrequest=require('request');// Set the headersvarheaders={'User-Agent':'Super Agent/0.0.1','Content-Type':'application/x-www-form-urlencoded'}// Configure the requestvaroptions={url:'http://samwize.com',method:'GET',headers:headers,qs:{'key1':'xxx','key2':'yyy'}}// Start the requestrequest(options,function(error,response,body){if(!error&&response.statusCode==200){// Print out the response bodyconsole.log(body)}})
varrequest=require('request');// Set the headersvarheaders={'User-Agent':'Super Agent/0.0.1','Content-Type':'application/x-www-form-urlencoded'}// Configure the requestvaroptions={url:'http://samwize.com',method:'POST',headers:headers,form:{'key1':'xxx','key2':'yyy'}}// Start the requestrequest(options,function(error,response,body){if(!error&&response.statusCode==200){// Print out the response bodyconsole.log(body)}})
To handle gzip encoded response, you will need the compress-buffer library.
1234567891011121314151617181920
varuncompress=require('compress-buffer').uncompress;// Set the headers and options ...request(options,function(error,response,body){if(!error&&response.statusCode==200){// Handle gzipvarencoding=response.headers['content-encoding']if(encoding&&encoding.indexOf('gzip')>=0){body=uncompress(body);}body=body.toString('utf-8');// Print out the response bodyconsole.log(body)// If it is jsonvarjson_body=JSON.parse(body);}})