nodejs發起https請求的同步寫法

nodejs發起https請求,查了官方文檔,寫法以下:javascript

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);
});

好比咱們如今要用微信登陸咱們的網站,寫法改動後變成:html

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 庫,java

var rp = require('request-promise');

而後代碼能夠簡化成這樣:node

rp(qurl)
         .then(function (htmlString) {
             // Process html...
              log.info('htmlString:'+htmlString);
         }) .catch(function (err) {
             // Crawling failed...
             log.info('err:'+err.stack);
         });
相關文章
相關標籤/搜索