比如我微信jssdk需要获取jsapi_ticket再组合后把signature返回给客户端,这个用koa需要怎么改写呢?比如我express如下代码需要怎么改写成koa呢?
// /config/wechat.cfg.js
module.exports = {
grant_type: 'client_credential',
appid: 'xxxxxxxxxxxxxxx',
secret: 'xxxxxxxxxxxxxxxxxxxxxxxxxx',
accessTokenUrl:'https://api.weixin.qq.com/cgi-bin/token',
ticketUrl:'https://api.weixin.qq.com/cgi-bin/ticket/getticket',
cache_duration:1000*60*60*2 //根据规定缓存时长为2小时
}
// signature.js
var request = require('request'),
cache = require('memory-cache'),
sha1 = require('sha1'),
config = require('./config/wechat.cfg');
exports.sign = function (url,callback) {
var noncestr = Math.random().toString(36).substr(2, 15),
timestamp = Math.floor(Date.now()/1000), //精确到秒
jsapi_ticket;
if(cache.get('ticket')){
jsapi_ticket = cache.get('ticket');
console.log('1' + 'jsapi_ticket=' + jsapi_ticket + '&noncestr=' + noncestr + '×tamp=' + timestamp + '&url=' + url);
callback({
noncestr:noncestr,
timestamp:timestamp,
url:url,
jsapi_ticket:jsapi_ticket,
signature:sha1('jsapi_ticket=' + jsapi_ticket + '&noncestr=' + noncestr + '×tamp=' + timestamp + '&url=' + url)
});
}else{
request(config.accessTokenUrl + '?grant_type=' + config.grant_type + '&appid=' + config.appid + '&secret=' + config.secret ,function(error, response, body){
if (!error && response.statusCode == 200) {
var tokenMap = JSON.parse(body);
request(config.ticketUrl + '?access_token=' + tokenMap.access_token + '&type=jsapi', function(error, resp, json){
if (!error && response.statusCode == 200) {
var ticketMap = JSON.parse(json);
cache.put('ticket',ticketMap.ticket,config.cache_duration); //加入缓存
console.log('jsapi_ticket=' + ticketMap.ticket + '&noncestr=' + noncestr + '×tamp=' + timestamp + '&url=' + url);
callback({
noncestr:noncestr,
timestamp:timestamp,
url:url,
jsapi_ticket:ticketMap.ticket,
signature:sha1('jsapi_ticket=' + ticketMap.ticket + '&noncestr=' + noncestr + '×tamp=' + timestamp + '&url=' + url)
});
}
})
}
})
}
}
// server.js
//引入配置和方法
var express = require('express')
var signature = require('./signature');
var wechat_cfg = require('./config/wechat.cfg');
var server = express();
.........(省略代码)
//增加一条api供客户端使用
server.get("/api/signature", function(req,res) {
const url = req.query.url.split('#')[0];
signature.sign(url,function(signatureMap){
//因为config接口需要appid,多加一个参数传入appid
signatureMap.appId = wechat_cfg.appid;
//发送给客户端
res.send(signatureMap);
});
})
.........(省略代码)
上面express的代码需要怎么用koa来改写呢?
我使用koa无法通过回调函数把请求回来的数据发送给客户端
//增加一条api供客户端使用
router.get("/api/signature", function *(next) {
const url = this.request.query.url.split('#')[0];
console.log(url);
signature.sign(url,function(signatureMap){
//因为config接口需要appid,多加一个参数传入appid
signatureMap.appId = wechat_cfg.appid;
//发送给客户端
this.body = signatureMap; //这一行会出错,估计this对象已经不一样了!通过外层传递this变量也是不行
});
})
其中this.body = signatureMap;
这一行会出错,估计this对象已经不一样了!通过外层传递this变量也是不行.求大神搭救!