nodejs发起https请求,查了官方文档,写法如下:
const https = require('https');
https.get('https://encrypted.google.com/', (res) => {
console.log('状态码:', res.statusCode);
console.log('请求头:', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
}).on('error', (e) => {
console.error(e);
});
比如我们现在要用微信登录我们的网站,写法改动后变成:
var qurl="https://api.weixin.qq.com/sns/oauth2/access_token?appid=myappid&secret=myscret&code="+
code+"&grant_type=authorization_code";
https.get(qurl, function (ress) {
var datas = [];
var size = 0;
ress.on('data', function (data) {
datas.push(data);
size += data.length;
//process.stdout.write(data);
});
ress.on("end", function () {
var buff = Buffer.concat(datas, size);
//var result = iconv.decode(buff, "utf8");//转码
var result = buff.toString();//不需要转编码,直接tostring
log.info('result:'+result);
return result;
});
}).on('err',function(err){
log.error(err.stack)
callback.apply(null);
});
写法还是有点不完美,方法执行完不能直接获取微信返回的 内容,因为目前的方法是异步的,不能保证顺序性,下面我们来换一种同步写法。首先需要依赖 request-promise 库,
var rp = require('request-promise');
然后代码可以简化成这样:
rp(qurl)
.then(function (htmlString) {
// Process html...
log.info('htmlString:'+htmlString);
}) .catch(function (err) {
// Crawling failed...
log.info('err:'+err.stack);
});