request module
request是一套實作http/https模組的http(s) client module,透過該套件可以快速的進行
Github repository
https://github.com/request/request
Installation
npm install request
Sample Usage
request最吸引人的地方莫過於使用pipe的function串接http資源,下面有兩個範例:
- 這個是透過request來串接resp(response),讓
app.get('/getpic/doodle.png', function(req, res) {
request.get('http://mysite.com/doodle.png').pipe(res);
});
- 或者是串連fs.createWriteStream來下載檔案
request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'));
除了一些基本功能外,request針對header, body, form, queryString等都有不錯的處理,可以參考下面範例:
單純的HTTP GET呼叫,其中get的callback,e=error, r=request, d=data
/** * error: 封裝錯誤內容 * request: 封裝呼叫的協定與相關資訊 * data: 回傳值 */ var request = require('request'); var url = 'http://micloud.tw'; request.get(url, function(e, r, d){ if(e) console.log(e); console.log(d); });
Request模組Pipe的用法
var request = require('request') , http = require('http') , url = 'http://micloud.tw' , resource = 'https://portal.micloud.tw/images/logo.png'; var server = http.createServer(function (req, resp) { if (req.url === '/logo.png') { if (req.method === 'PUT') { req.pipe(request.put(resource)) } else if (req.method === 'GET' || req.method === 'HEAD') { request.get(resource).pipe(resp) } } }).listen(8000);
透過Request來做簡單的Reverse Proxy
var http = require('http') , request = require('request'); //google site url var url = 'https://sites.google.com/site/'; //google site domain (change to yours) url += 'simonsumail'; http.createServer(function (req, resp) { console.log(req.url); if (req.method === 'PUT') { req.pipe(request.put(url + req.url)) } else if (req.method === 'GET' || req.method === 'HEAD') { request.get(url + req.url).pipe(resp); } }).listen(80); //ipaddress that the node server host