17koa / koa-generator-examples Goto Github PK
View Code? Open in Web Editor NEW一起学koa
Home Page: http://17koa.com/koa-generator-examples/
License: MIT License
一起学koa
Home Page: http://17koa.com/koa-generator-examples/
License: MIT License
在实现一个功能时会使用很多第三方模块,即便是官方推荐的模块列表,每种功能都能对应出大量模块。
比如,上传那一章里就说到用版本小于1的koa-multer,但是人气更高也好用的上传模块也很多,这年头选择恐惧的人这么多,是不是应该做个同功能模块的比较,或说下使用这个模块的原因,或是这个模块的优点?
koa2怎么使用koa-router?
Post with form-data(已完成)
some code...
app.use(function *(next){
console.log("-+-+-+-+-+-+");
console.log(this.method);
yield next;
this.body = "hello world world world!";
console.log("------");
});
app.use(route.get('/products',function *(){
console.log("hahaha");
console.log(this.method);
console.log("hehehehe");
}));
app.use(function *(){
console.log('999');
this.body = "hello world!";
console.log(this.method);
console.log("++++++");
});
我想请问的是:为什么写在route前面的函数被调用了两次呢?如果放在后面的话,倒是没有这个问题;
测试了下node的文件都包裹了function, class写在里面会报SyntaxError错误 貌似是function里面不能定义class。。。
rt
Hola! @i5ting has created a ZenHub account for the 17koa organization. ZenHub is the only project management tool integrated natively in GitHub – created specifically for fast-moving, software-driven teams.
To get set up with ZenHub, all you have to do is download the browser extension and log in with your GitHub account. Once you do, you’ll get access to ZenHub’s complete feature-set immediately.
ZenHub adds a series of enhancements directly inside the GitHub UI:
Still curious? See more ZenHub features or read user reviews. This issue was written by your friendly ZenHub bot, posted by request from @i5ting.
part1 增加class细节
运行之后会报错,提示missing script: 1
app.use(function *(){
this.demo = 'test text';
});
app.use(function *(){
this.body = this.demo;
});
这块代码有误,前一个中间件必须手动调用next,才能保证他的向下运行,正确示例如下:
app.use(function *(next){
this.demo = 'test text';
yield next;
});
app.use(function *(){
this.body = this.demo;
});
rt
arrow function只是es6 function enhancement的一个部分,能不能把这个章节的题目修改成“函数扩展”?期待大家的回复。
class Test{
saySomething() { return "abc"; }
get [Symbol.unscopables] {
return {saySomething: true};
}
}
get [Symbol.unscopables] 后面少了一个()
const Koa = require('koa');
const app = new Koa();
// logger
app.use(async (ctx, next) => {
const start = new Date;
await next();
const ms = new Date - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}`);
});
// response
app.use(ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
如上代码,用babel-node运行时,报下面错误
C:\Users\YreenChan\AppData\Roaming\npm\node_modules\babel-cli\node_modules\babel
-core\lib\transformation\file\index.js:548
throw err;
^
SyntaxError: E:/xampp/htdocs/www/nodejs/koajs2/test.js: Unexpected token (6:26)
�[0m 4 | �[90m// logger�[39m
5 |
> 6 | app�[1m.�[22muse�[94m�[1m(�[22m�[39masync �[94m�[1m(�[22m�[39mctx�[1m,�[22
m next�[94m�[1m)�[22m�[39m �[1m=>�[22m �[32m{�[39m
| ^
7 | �[36mconst�[39m start �[1m=�[22m �[36mnew�[39m Date�[1m;�[22m
8 | await next�[94m�[1m(�[22m�[39m�[94m�[1m)�[22m�[39m�[1m;�[22m
9 | �[36mconst�[39m ms �[1m=�[22m �[36mnew�[39m Date �[1m-�[22m start�[1m;�[
22m�[0m
at Parser.pp.raise (C:\Users\YreenChan\AppData\Roaming\npm\node_modules\babe
l-cli\node_modules\babylon\index.js:1413:13)
at Parser.pp.unexpected (C:\Users\YreenChan\AppData\Roaming\npm\node_modules
\babel-cli\node_modules\babylon\index.js:2895:8)
at Parser.pp.parseAsyncArrowFromCallExpression (C:\Users\YreenChan\AppData\R
oaming\npm\node_modules\babel-cli\node_modules\babylon\index.js:593:47)
at Parser.pp.parseSubscripts (C:\Users\YreenChan\AppData\Roaming\npm\node_mo
dules\babel-cli\node_modules\babylon\index.js:544:21)
at Parser.pp.parseExprSubscripts (C:\Users\YreenChan\AppData\Roaming\npm\nod
e_modules\babel-cli\node_modules\babylon\index.js:511:15)
at Parser.pp.parseMaybeUnary (C:\Users\YreenChan\AppData\Roaming\npm\node_mo
dules\babel-cli\node_modules\babylon\index.js:481:19)
at Parser.pp.parseExprOps (C:\Users\YreenChan\AppData\Roaming\npm\node_modul
es\babel-cli\node_modules\babylon\index.js:412:19)
at Parser.pp.parseMaybeConditional (C:\Users\YreenChan\AppData\Roaming\npm\n
ode_modules\babel-cli\node_modules\babylon\index.js:394:19)
at Parser.pp.parseMaybeAssign (C:\Users\YreenChan\AppData\Roaming\npm\node_m
odules\babel-cli\node_modules\babylon\index.js:357:19)
at Parser.pp.parseExprListItem (C:\Users\YreenChan\AppData\Roaming\npm\node_
modules\babel-cli\node_modules\babylon\index.js:1224:16)
用restify与express有一年多了,一直在考虑什么时候上koa与es6,看到你这个项目,很有兴趣。
暂定我来实现一个mysql的操作demo,我同时也在关注postgresql,建议项目可以增加postgresql这个条目,我也可以提供代码。
写过一个,考完试回去整理一下。
RT
看这里的md,没有源码分析的部分,下面的文章应该怎么贡献出来?
如图,看上去不错,而且开源项目是免费的。不过,竟然是chrome 插件来实现的,https://www.zenhub.io/。@_@
class Polygon{
constructor(height, width){
this.height = height;
this.width = width;
}
get name(){
return this.name;
}
set name(somename){
this.name = somename;
}
}
比如我微信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变量也是不行.求大神搭救!
配置项里有
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.