使用nodegrass簡單封裝http請求例子

來源:互聯網
上載者:User

標籤:style   blog   http   io   color   ar   os   使用   sp   

1、項目中經常性的使用http發送請求處理資料。而大部分請求方式為get和post,於是對http請求進行封裝,提供代碼的利用率。

2、nodegress是nodejs的一個請求工具。

具體步驟及代碼如下:

1、安裝nodegrass,執行npm install nodegrass命令。

2、封裝過程中存在使用資料集合工具underscore工具,先進行安裝。

3、nodegrass中post及get代碼如下:

NodeGrass.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";    }}//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";    }}

4、http的具體封裝,代碼如下:

var ng = require(nodegrass);var $ = require(underscore);var domain = http://www.*******.com;exports.header = {    Content-Type: application/x-www-form-urlencoded};exports.get = function (url, data, success) {    ajax(url, get, data, success);};exports.post = function (url, data, success) {    ajax(url, post, data, success);};function ajax(url, httpMethod, data, success) {    var args = [function (res, status, headers) {        try {            var json = JSON.parse(res);            success(json, headers);        }        catch(ex) {            if(res.success)                console.log(ajax fail: %s, url);        }    }, exports.header];    if (httpMethod == get) {        args.unshift([            domain,            url,            ?,             $.map(data, function (v, k) {                return [k, v].join(=);            }).join(&)        ].join(‘‘));    }    else {        data._ = ‘‘;        args.unshift(domain + url);        args.push(data);    }    args.push(utf8);    ng[httpMethod].apply(ng, args).on(error, function () {        console.log(ajax error: %s, url);    });}

根據node-grass中的具體post及get請求的代碼,對ajax進行模仿封裝。

1、一般為一個固定的URL首碼請求,直接domain定義。

2、每個請求都有固定的header標籤。

3、http包含get、post請求兩種方式。

4、http包含

url:請求地址,

httpMothed:請求方式(post,get)

data:請求資料

success:成功與否執行的回呼函數

5、其中對data的拼接方式使用"?","&"字元進行拼接處理。

6、此外還須標明字元集為“utf8”的字元集

7、同時還有錯誤時所需要輸出的錯誤資訊提示。

具體調用方式樣本,代碼如下:

var ajax = require(‘./ajax‘);
  ajax.post(‘/user/save‘, s, function (resp) {                if (!resp.success) {                    console.log("error");                }                console.log("success");            });    

如此可以輕鬆快速的類比請求處理相應資料。

 

以上例子根據nodegrassAPI進行編寫,如有不足之處,敬請原諒。

 

使用nodegrass簡單封裝http請求例子

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.