2012年5月31日 星期四

使用原生的http request進行post form呼叫

使用原生的http request進行post form呼叫:

var qs = require('querystring');
var http = require('http');

// Base authentication
var username = 'your_username';
var password = 'your_password';
var auth = 'Basic ' + new Buffer(username + ':' + password).toString('base64');

// The connection parameters
var opts = {
 host:"your.server.ip.address",
 port: 80,
 method: 'POST',
 path: "/your_path",
 headers :
  {
    "Authorization": auth ,
    "Content-Type":"application/x-www-form-urlencoded; charset=utf-8",
    "Content-Length": 0
  }
};

// Example function
exports.your_function = function(param1, ..., callback){
  // Process your business logic for params...
  // The post form parameters
  var form_params = {
    field1 : "value 1",
    field2 : "value 2",
    ...
  };

  var params = qs.stringify(form_params);
  opts.headers['Content-Length'] = params.length;

  var req = http.request(opts, function(res){
    console.log('STATUS: ' + res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));
    res.setEncoding('utf8');
  });

  req.on('response', function(res){
    res.body = '';
    res.setEncoding('utf-8');
    res.on('data', function (chunk) {
      res.body += chunk;
    });
    
    // Trigger the callback
    res.on('end', function(){
      callback(res.body, res);
    });
  });

  req.on('error', function(e) {
    console.log('problem with request: ' + e.message);
  });

  // write data to request body
  req.write(params);
  req.write('data\n');
  req.end();
}

// Usage of sample function
this.your_function(
    param1, ..., 
    function(body, res){
      console.log(body);
      console.log('>>>>>>>>>>>'+res.headers['Content-Type']);
    }
);