GithubHelp home page GithubHelp logo

17koa / koa-generator-examples Goto Github PK

View Code? Open in Web Editor NEW
482.0 482.0 76.0 2.93 MB

一起学koa

Home Page: http://17koa.com/koa-generator-examples/

License: MIT License

JavaScript 95.65% CSS 1.46% HTML 2.41% Batchfile 0.49%

koa-generator-examples's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

koa-generator-examples's Issues

请问下koa怎么把网络请求后的回调函数里面的数据发送回客户端呢?

比如我微信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 + '&timestamp=' + timestamp + '&url=' + url);
        callback({
            noncestr:noncestr,
            timestamp:timestamp,
            url:url,
            jsapi_ticket:jsapi_ticket,
            signature:sha1('jsapi_ticket=' + jsapi_ticket + '&noncestr=' + noncestr + '&timestamp=' + 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 + '&timestamp=' + timestamp + '&url=' + url);
                        callback({
                            noncestr:noncestr,
                            timestamp:timestamp,
                            url:url,
                            jsapi_ticket:ticketMap.ticket,
                            signature:sha1('jsapi_ticket=' + ticketMap.ticket + '&noncestr=' + noncestr + '&timestamp=' + 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变量也是不行.求大神搭救!

mysql 基本操作

用restify与express有一年多了,一直在考虑什么时候上koa与es6,看到你这个项目,很有兴趣。
暂定我来实现一个mysql的操作demo,我同时也在关注postgresql,建议项目可以增加postgresql这个条目,我也可以提供代码。

其实一直有这种问题

在实现一个功能时会使用很多第三方模块,即便是官方推荐的模块列表,每种功能都能对应出大量模块。
比如,上传那一章里就说到用版本小于1的koa-multer,但是人气更高也好用的上传模块也很多,这年头选择恐惧的人这么多,是不是应该做个同功能模块的比较,或说下使用这个模块的原因,或是这个模块的优点?

Getting more done in GitHub with ZenHub

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.


How do I use ZenHub?

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.

What can ZenHub do?

ZenHub adds a series of enhancements directly inside the GitHub UI:

  • Real-time, customizable task boards for GitHub issues;
  • Multi-Repository burndown charts, estimates, and velocity tracking based on GitHub Milestones;
  • Personal to-do lists and task prioritization;
  • Time-saving shortcuts – like a quick repo switcher, a “Move issue” button, and much more.

Add ZenHub to GitHub

Still curious? See more ZenHub features or read user reviews. This issue was written by your friendly ZenHub bot, posted by request from @i5ting.

ZenHub Board

用babel-node运行官方例子报错

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)

第二章koa应用初见代码有误

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

请教一个关于中间件的运行流程问题,函数被重复执行了;

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("++++++");
});

other code...
控制台的结果:
image

我想请问的是:为什么写在route前面的函数被调用了两次呢?如果放在后面的话,倒是没有这个问题;

在node中如何使用class?

测试了下node的文件都包裹了function, class写在里面会报SyntaxError错误 貌似是function里面不能定义class。。。

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.