node.js发送http协议与https协议

2019-06-10  本文已影响0人  pawn_c

首先是发送http协议代码如下:

var http = require('http');  
  
var qs = require('querystring');  

//这是需要提交的数据  
var data = {  
    a: 123,  
    time: new Date().getTime()};
  
  
var content = qs.stringify(data);  
  
var options = {  
    hostname: '127.0.0.1',  
    port: 10086,  
    path: '/pay/pay_callback?' + content,  
    method: 'GET'  
};  
  
var req = http.request(options, function (res) {  
    console.log('STATUS: ' + res.statusCode);  
    console.log('HEADERS: ' + JSON.stringify(res.headers));  
    res.setEncoding('utf8');  
    res.on('data', function (chunk) {  
        console.log('BODY: ' + chunk);  
    });  
});  
  
req.on('error', function (e) {  
    console.log('problem with request: ' + e.message);  
});  
  
req.end();

但是有时候需要我们发送https请求,比如微信的验证连接,代码如下:

onLogin(getreq,getres){
        var getdata = url.parse(getreq.url, true).query;
        console.log(getdata.code);
        

        //APPID和SECRET从官方获取
        var requesturl = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code="+getdata.code+"&grant_type=authorization_code";
         https.get(requesturl, function (res) {  
                     var datas = [];  
                     var size = 0;  
                res.on('data', function (data) {  
                             datas.push(data);  
                             size += data.length;
                });
                 res.on("end", function () {  
                              var buff = Buffer.concat(datas, size);  
                              var result = iconv.decode(buff, "utf8");
                     // console.log(result);
                        getres.write(result,"utf-8");
                        getres.end();
                             });  
                 }).on("error", function (err) {  
                             Logger.error(err.stack)  
                             callback.apply(null);  
                });  

    
    }
上一篇 下一篇

猜你喜欢

热点阅读