With this post, I will write about using simple Example Code GET and POST in Node.js. In this post, I use this library (Simplified HTTP request client.) And here is the code:
GET
var request = require('request');
// Set the headers
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/x-www-form-urlencoded'
}
// Configure the request
var options = {
url: 'http://hostforlife.eu',
method: 'GET',
headers: headers,
qs: {'key1': 'xxx', 'key2': 'yyy'}
}
// Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Print out the response body
console.log(body)
}
})
Above code will do GET https://localhost:8080/?key1=xxx&key2=yyy
POST
var request = require('request');
// Set the headers
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/x-www-form-urlencoded'
}
// Configure the request
var options = {
url: 'http://hostforlife.eu',
method: 'POST',
headers: headers,
form: {'key1': 'xxx', 'key2': 'yyy'}
}
// Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Print out the response body
console.log(body)
}
})
Above code will do POST https://localhost:8080/ with key1=xxx&key2=yyy in the body.
Handling gzip encoding
To handle gzip encoded response, you will need the compress-buffer library.
var uncompress = require('compress-buffer').uncompress;
// Set the headers and options ...
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Handle gzip
var encoding = response.headers['content-encoding']
if(encoding && encoding.indexOf('gzip')>=0) {
body = uncompress(body);
}
body = body.toString('utf-8');
// Print out the response body
console.log(body)
// If it is json
var json_body = JSON.parse(body);
}
})
HostForLIFE.eu Node.js Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.