使用 koa

环境

nodejs: v0.12.7
koa: v0.21.0

koa 是这样介绍自己的

Koa 应用是一个包含中间件 generator 方法数组的对象。当请求到来时, 这些方法会以 stack-like 的顺序执行, 从这个角度来看,Koa 和其他中间件系统(比如 Ruby Rack 或者 Connect/Express )非常相似. 然而 Koa 的一大设计理念是: 通过其他底层中间件层提供高级「语法糖」,而不是Koa. 这大大提高了框架的互操作性和健壮性, 并让中间件开发变得简单有趣.

相比 express, koa 是一个非常精简的 web 框架,需要的中间件都可以自己造。koa 的 generator 委托的实现是基于 TJ 大神的 co

测试代码-日志中间件:

var koa = require('koa');
var app = koa();

function logger() {
    return function * (next) {
        if ('/' != this.path) {
            return;
        }

        var start = new Date;
        yield next;
        var ms = new Date - start;
        console.log('URL:', this.url, " TIME:", ms, 'ms');
    };
}

app.use(logger());

app.use(function * () {
    this.body = 'hello koa';
});

app.listen(4000);

启动、访问
这里写图片描述

[root@nginx koa]# node --harmony app.js
URL: /  TIME: 4 ms

测试代码-404中间件

var koa = require('koa');
var app = koa();

function pageNotFound() {
    return function * (next) {
        yield next;

        if (404 != this.status) {
            return;
        }

        this.status = 404;

        switch (this.accepts('html', 'json')) {
            case 'html':
                this.type = 'html';
                this.body = '<p>Page Not Found</p>';
                break;
            case 'json':
                this.body = {
                    message: 'Page Not Found'
                };
                break;
            default:
                this.type = 'text';
                this.body = 'Page Not Found';
        }
    }
}

app.use(pageNotFound());

app.use(function * () {
    if ('/' == this.path) {
        this.body = 'hello koa';
    }
});

app.listen(4000);

这里写图片描述
使用 koa (其实是 co 的功劳),可以方便的将异步的回调的代码写成非阻塞的顺序的代码。
koa 例子

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值