2012年5月31日 星期四

使用request套件進行http post request

使用request套件進行http post request,範例中始用到HTTP Base Authentication,如無需要,可移除Headers中的Authorization部分敘述:

1. 安裝request套件
npm install request

2. 範例執行檔案
var request = require('request');
var qs = require('querystring');

// Base Authentication
var username = 'yourname';
var password = 'yourpasswd';
var auth = 'Basic ' + new Buffer(username + ':' + password).toString('base64');

// Base url of you will request (include protocol, address, port, path and the lastest of '?')

// Your form fields 
var params = {
  field_A : "value a",
  field_B : "value b",
  headers: { "Authorization": auth }
}

// Append query string to your url
url += qs.stringify(params);

// Your customize function
exports.your_function1 = function(param1,..., callback) {
  //process params...
  request.post(url, params, function (e, r, body) {
      if(callback)
        callback(e, r, body);
  });
}

// Usage of your customize function:
this.your_function1(param1, ..., function(e,r,body) {
  //Process your responses
  //ex:
  console.log(body);
  console.log(r.headers['Content-Type']);
});