首先是發(fā)送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();
但是有時候需要我們發(fā)送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);
});
}