var app = koa();//创建不需要new
//中间件中yield next 将控制权交给下一个符合的中间件。
//当最终的中间件执行完,会去执行被挂起的next后的代码。一直逆推而上。
//以下执行顺序 aa bb body 逆推 输出时间 最后cc
app.use(function *(next){
console.log('aa');
yield next;
console.log('cc')
})
app.use(function *(next){
var start = new Date;
console.log('bb')
yield next;
var ms = new Date - start;
console.log('%s %s - %s', this.method, this.url, ms);
});
app.use(function *(){
for(var i=0;i<999999;i++){}
this.body="hell world"
})
app.listen(3001);
use 内的this表示当前访问对象,this.request 请求对象,this.response 返回对象。
this.path 目录,this.method 请求方式,this.cookies.set() this.body 设置返回内容。
-----------------------koa-router
var Router=require('koa-router');
var myrouter=new Router();
myrouter.get('/',function *(next){
this.body="首页";
})
myrouter.get('/about',function *(next){
this.body='about'
})
//路由参数
myrouter.get('/user/:id',function *(next){
this.body=this.params.id;
})
app.use(myrouter.routes())
--------------静态目录
var staticserver=require('koa-static');
var path=require('path');
app.use(staticserver(path.join(__dirname,'public')))
--------ejs
var render = require('koa-ejs');
render(app,{
root: path.join(__dirname, 'views'),
layout:'template',//母版
viewExt:'html',
catch:false,
debug:true
});
//中间件内创建state 对象在ejs内可以访问
//但需要用yield
app.use(function *(next){
this.state=this.state || {};
this.state.ip=this.ip;
this.state.method=this.method
yield next;
console.log('a')
})
//当访问index 时渲染index ejs
app.use(function *(){
var users = [{name: 'Dead Horse'}, {name: 'Jack'}, {name: 'Tom'}];
yield this.render('index',{layout:false,title:'index',users:users})
})
母版内需要用: <%- body%>来显示渲染的模板。
模板里通过<%=%>来显示值
还可以引用其他模板
<% include content.html %>
引用模板内可以获取引用模板的数据
而在use内定义的this.state对象可以通过<%=%>来获取到。
-----------koa-session
var session = require('koa-session');
//sessoin配置时需要Keys
app.keys = ['some secret hurr'];//设置签名Cookie密钥,该密钥会被传递给 KeyGrip。
app.use(session(app));//session
this.session.XX来设置或获取值。
this.redirect() 跳转
cookie不需要配置直接this.cookies.get set 来操作。
-----------------koa 和http
把koa绑定在http上。
var app=koa();
var server = require('http').Server(app.callback());
server.listen(3001)
-----------------koa和socket
在上边的基础上只需:
var io = require('socket.io')(server);
//io.use内通过socket.request.headers.cookie 来获取页面cookie