nodejs 封装网络请求

@fright  December 1, 2017
function postData(url,param,success,type){
  
    var querystring = require('querystring')
    var URL = require('url');
    var os = require('os');
    //处理参数
    var postData;
    if (typeof param == 'string'){
        postData = param;
    }else{
        postData = querystring.stringify(param);
    }
    var postDataArr = querystring.parse(postData);

    postDataArr.timestamp = Date.parse(new Date())/1000;
    postDataArr.app_id = config.api.appid;
    postDataArr.format = 'json';
    postDataArr.distributorId = 1;
    postData = querystring.stringify(postDataArr);
    //开始写入加载.....
    url = URL.parse(url);
    url.headers = {
        'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
        'Content-Length':Buffer.byteLength(postData),
        'User-Agent' : os.platform()+'-Vesion:'+config.version.value+'-company-'+$("#currentUrl").val()  //自定义User-Agent信息
    }
    const options = url;  //访问地址
    var results = '';

    const req = http.request(options, function(res){
        res.setEncoding('utf8');
        res.on('data',function(data){
            results+=data;
        });
    
        res.on('end', () => {
            if (type!='string'){
                results = JSON.parse(results);
            }
            success(results);
            //隐藏加载中....
        });
    });
    req.on('error', (e) => {
        alertError(`请求遇到问题: ${e.message}`,false,5000);
        return false;
        //console.error(`请求遇到问题: ${e.message}`);
    });
    // 写入数据到请求主体
    req.write(postData);
    req.end();
}

function getData(url,success,type){
    //get 请求外网
    http.get(url,function(req,res){
        var html='';
        req.on('data',function(data){
            html+=data;
        });
        req.on('end',function(){
            if (type=='string'){
            }else{
                html = JSON.parse(html);
            }
            success(html);
        });
    });

}

评论已关闭