请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

Cannot find module 'request'引入出错

我已经知道原因了:还是要安装request包的= =


在引入request时候总是报错,但是已经安装bluebird了。而且去看了bluebird官网发现引用改为var Promise = require("bluebird"); Promise.promisifyAll(require("request")); 引入还是出错,希望老师帮忙解答一下。

var sha1 = require('sha1');

var Promise = require("bluebird");

Promise.promisifyAll(require("request"));


var prefix = "https://api.weixin.qq.com/cgi-bin/";

var api = {

  access_token:prefix+"token?grant_type=client_credential"

}


function Wechat(opts) {

  var that = this;

  this.appID = opts.appID;

  this.appSecret = opts.appSecret;

  this.getAccessToken = opts.getAccessToken;

  this.saveAccessToken = opts.saveAccessToken;

  this.getAccessToken()

    .then(function (data) {

      try{

        data = JSON.parse(data)

      }

      catch(e) {

        return that.updateAccessToken(data);

      }

      if(that.isValueAccessToken(data) ){

        Promise.resolve(data)

      } else {

        return that.updateAccessToken();

      }

    })

    .then(function(data) {

      that.access_token = data.access_token;

      that.expires_in = data.expires_in;

      that.saveAccessToken(data)

    })

}


Wechat.prototype.isValueAccessToken = function(data) {

    if(!data || !data.access_token || !data.expires_in) return false;

    var access_token = data.access_token;

    var expires_in = data.expires_in;

    var now = (new Date().getTime());

    if (now < expires_in) {

      return true

    } else {

      return false

    }

}

Wechat.prototype.updateAccessToken = function(data) {

  var appID = this.appID;

  var appSecret = this.appSecret;

  var url = api.access_token + "&appid=" + appID + "&secret=" + appSecret;


  return new Promise(function(resolve,reject){

    request.getAsync({url: url,json:true}).then(function(responce) {

      var data = responce[1];

      var noe = (new Date().getTime());

      var expires_in = now + (data.expires_in - 20)*1000;

      data.expires_in = expires_in;


      resolve(data);

    })


  })

}

module.exports = function (opts) {

  var Wechat = new Wechat(opts);//管理和微信接口


  return async ctx => {

    console.log(ctx.query)

    var token = opts.token;

    var signature = ctx.query.signature;

    var nonce = ctx.query.nonce;

    var timestamp = ctx.query.timestamp;

    var echostr = ctx.query.echostr;

    var str = [token,timestamp,nonce].sort().join('');

    var sha = sha1(str);

    if (sha === signature) {

      ctx.body = echostr +'';

    } else {

      ctx.body = 'wrong'

    }

  }

}


正在回答 回答被采纳积分+3

1回答

Scott 2017-08-07 21:18:59

可以直接用 request-promise 吧


const rp = require('request-promise')


rp.get().then() 这样用

0 回复 有任何疑惑可以回复我~
问题已解决,确定采纳
还有疑问,暂不采纳
意见反馈 帮助中心 APP下载
官方微信