標籤:style blog http io color ar os 使用 sp
最近做資料匯入,須類比http請求,調用架構的相應方法進行資料的插入及儲存操作。
採用nodejs的nodegrass方法進行相應簡單模仿。
1、搭建nodejs環境。
2、執行npm install nodegrass命令。
3、引入模組,var ng= require(nodegrass);
4、下面先看nodegrass底層的get方法的具體實現,代碼如下:
//Get Method Request//Support HTTP and HTTPS request,and Automatic recognition//@Param url//@Param callbackNodeGrass.prototype.get = function(url,callback, reqheaders, charset){ var protocol = getProtocol(url); var _defaultCharSet = ‘utf8‘; if(typeof charset === ‘string‘ ){ _defaultCharSet = charset; } if(typeof(reqheaders) === "string" && charset === undefined) { _defaultCharSet = reqheaders; } var newheader = {}; if(reqheaders !== undefined && typeof(reqheaders) === "object") { for(var ele in reqheaders) { newheader[ele.toLowerCase()] = reqheaders[ele]; } } newheader["content-length"] = 0; var options = { host:getHost(url), port:getPort(url), path:getPath(url), method:‘GET‘, headers:newheader }; if(protocol === http || protocol === https){ return _sendReq(protocol,null,options,_defaultCharSet,callback); }else{ throw "sorry,this protocol do not support now"; }}
從中可以看出,只需要在方法調用中,加入如下參數即可:
url請求地址,
callback回呼函數,
reqheaders要求標頭標識,一般使用 ‘Content-Type‘: ‘application/x-www-form-urlencoded‘
charset編碼方式,一般為utf8
對應的post請求的底層實現代碼如下:
//Post Method Request//Support HTTP and HTTPS request,and Automatic recognition//@Param url//@Param callback//@Param header//@param postdataNodeGrass.prototype.post = function(url,callback,reqheaders,data,charset){ var protocol = getProtocol(url); var _defaultCharSet = ‘utf8‘; if(typeof charset === ‘string‘ ){ _defaultCharSet = charset; } if(typeof(data) === ‘object‘){data = querystring.stringify(data);} var options={ host:getHost(url), port:getPort(url), path:getPath(url), method:‘POST‘, headers:reqheaders }; if(protocol === http || protocol === https){ return _sendReq(protocol,data,options,_defaultCharSet,callback) }else{ throw "sorry,this protocol do not support now"; }}
從中可以看出,只需要在方法調用中,加入如下參數即可:
url請求地址,
callback回呼函數,
reqheaders要求標頭標識,一般使用 ‘Content-Type‘: ‘application/x-www-form-urlencoded‘
data請求所包含的具體資料,
charset編碼方式,一般為utf8
下面以post方式模仿登入請求為例,代碼如下:
var ng = require(‘nodegrass‘);var REQ_HEADERS = { ‘Content-Type‘: ‘application/x-www-form-urlencoded‘};ng.post("http://******/user/login", function (res, status, headers) { if (res.success) { console.log("登入成功。"); } else { console.log("登入失敗。"); } }, REQ_HEADERS, {name: ‘*****‘, pwd: ‘***‘, rememberPwd: true}, ‘utf8‘). on(‘error‘, function (e) { console.log("Got error: " + e.message); });
此簡單例子根據nodegrass的API為根據書寫,如有不足之處,還請原諒。
菜鳥在前進,每天進步一點點。
nodejs模仿http請求組件nodegrass簡單例子