nodejs模仿http请求组件nodegrass简单例子

最近做数据导入,须模拟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 callback
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";
    }

}

从中可以看出,只需要在方法调用中,加入如下参数即可:

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 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";
    }
}

从中可以看出,只需要在方法调用中,加入如下参数即可:

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为根据书写,如有不足之处,还请原谅。

菜鸟在前进,每天进步一点点。