使用nodegrass简单封装http请求例子

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 postdata
NodeGrass.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进行编写,如有不足之处,敬请原谅。

原文地址:https://www.cnblogs.com/diaosizhang/p/4102953.html