求问老师:this.getAccessToken is not a function 错误
来源:4-4 第四天 上传临时素材之图片和视频
落叶无痕
2016-07-25
'use strict' var Promise=require('bluebird') var fs=require('fs') var request=Promise.promisify(require('request')) var xmlopr=require('./xmlopr') var prefix='https://api.weixin.qq.com/cgi-bin/' var api={ accessToken:prefix+'token?grant_type=client_credential', upload:prefix+'media/upload?' } function Wechat(opts){ this.appID=opts.appID this.appSecret=opts.appSecret this.getAccessToken=opts.getAccessToken this.saveAccessToken=opts.saveAccessToken this.fetchAccessToken() } Wechat.prototype.fetchAccessToken=function(data){ var that=this if(this.access_token&&this.expires_in){ if(this.isValidAccessToken(this)){ return Promise.resolve(this) } } this.getAccessToken() .then(function(data){ try{ data=JSON.parse(data) } catch(e){ return that.updateAccessToken() } if(that.isValidAccessToken){ return 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) return Promise.resolve(data) }) } Wechat.prototype.isValidAccessToken=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.accessToken+'&appid='+appID+'&secret='+appSecret return new Promise(function(resolve,reject){ request({url:url,json:true}).then(function(response){ var data=response.body var now=(new Date().getTime()) var expires_in=now+(data.expires_in-20)*1000 data.expires_in=expires_in resolve(data) }) }) } Wechat.prototype.uploadMaterial=function(type,filePath){ var that=this var form={ media:fs.createReadStream(filePath) } var appID=this.appID var appSecret=this.appSecret return new Promise(function(resolve,reject){ that .fetchAccessToken() .then(function(data){ var url=api.accessToken+'&access_token='+data.access_token+'&type='+type request({method:'POST',url:url,formData:form,json:true}).then(function(response){ var _data=response.body if(_data){ resolve(_data) }else{ throw new Error('Upload material fails') } }) .catch(function(err){ reject(err) }) }) }) } Wechat.prototype.reply=function(){ var content=this.body; var message=this.weixin; var xml=xmlopr.tpl(content,message); this.status=200; this.type='application/xml'; this.body=xml; } module.exports=Wechat;
报错,显示 this.getAccessToken is not a function
写回答
2回答
-
this.getAccessToken()
.then(function(data){
的 this 前面需要加 return
012016-07-27 -
落叶无痕
提问者
2016-07-27
其实开始通过查看其他同学的提问,也加上去了,可是没有什么反应,后来换了一个端口正常了,不太清楚什么原因
00
相似问题