nodejs模仿http请求组件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

封装代码如下:

var nodegrass = require('nodegrass');
var REQ_HEADERS = {
'Content-Type' : 'application/x-www-form-urlencoded'
}; // get请求
exports.ngGet = function(url, params, encoding) {
if (!encoding) {
encoding = "UTF-8";
}
var result = "";
nodegrass.get(url, function(data, status, headers) {
console.log(status);
console.log(headers);
console.log(data);
result = data;
}, REQ_HEADERS, params, encoding).on('error', function(e) {
console.log("Got error: " + e.message);
});
return result;
}; // post请求
exports.ngPost = function(url, params, encoding) {
if (!encoding) {
encoding = "UTF-8";
}
var result = "";
nodegrass.post(url, function(data, status, headers) {
console.log(status);
console.log(headers);
console.log(data);
result = data;
}, REQ_HEADERS, params, encoding).on('error', function(e) {
console.log("Got error: " + e.message);
}); return result;
}

  

上一篇:win10 安装visual studio 2015遇到的坑


下一篇:aliyun mysql