二、路由
2.1 原生路由
网站一般都有多个页面。通过ctx.request.path可以获取用户请求的路径,由此实现简单的路由
const main = ctx => {
if (ctx.request.path !== '/') {
ctx.response.type = 'html';
ctx.response.body = '<a href="/">Index Page</a>';
} else {
ctx.response.body = 'Hello World';
}
};
运行这个 demo。
$ node demos/05.js
访问 http://127.0.0.1:3000/about ,可以看到一个链接,点击后就跳到首页。
2.2 koa-route 模块
原生路由用起来不太方便,我们可以使用封装好的koa-route模块
// demos/06.js
const route = require('koa-route');
const about = ctx => {
ctx.response.type = 'html';
ctx.response.body = '<a href="/">Index Page</a>';
};
const main = ctx => {
ctx.response.body = 'Hello World';
};
app.use(route.get('/', main));
app.use(route.get('/about', about));
上面代码中,根路径/的处理函数是main,/about路径的处理函数是about。
运行这个demo
$ node demos/06.js
访问 http://127.0.0.1:3000/about ,效果与上一个例子完全相同。
2.3 静态资源
如果网站提供静态资源(图片、字体、样式表、脚本…),为它们一个个写路由就很麻烦,也没必要。koa-static模块封装了这部分的请求
// demos/12.js
const path = require('path');
const serve = require('koa-static');
const main = serve(path.join(__dirname));
app.use(main);
运行这个 Demo。
$ node demos/12.js
访问 http://127.0.0.1:3000/12.js,在浏览器里就可以看到这个脚本的内容。
2.4 重定向
有些场合,服务器需要重定向(redirect)访问请求。比如,用户登陆以后,将他重定向到登陆前的页面。**ctx.response.redirect()**方法可以发出一个302跳转,将用户导向另一个路由
// demos/13.js
const redirect = ctx => {
ctx.response.redirect('/');
ctx.response.body = '<a href="/">Index Page</a>';
};
app.use(route.get('/redirect', redirect));
执行这个demo
$ node demos/13.js
访问 http://127.0.0.1:3000/redirect ,浏览器会将用户导向根路由,并且ctx.response.body 中的内容将显示在首页上
三、中间件
3.1 Logger 功能
Koa 的最大特色,也是最重要的一个设计,就是中间件(middleware)。
Logger是其中的中间件之一,其功能是:打印日志
最简单的写法就是在main函数里面增加一行
// demos/07.js
const main = ctx => {
console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`);
ctx.response.body = 'Hello World';
};
运行这个demo
$ node demos/07.js
访问 http://127.0.0.1:3000 ,命令行就会输出日志。
1502144902843 GET /
打印现在的时间, 请求的方法是GET,请求的路径是根路径
3.2 中间件的概念
上一个例子里面的 Logger 功能,可以拆分成一个独立函数
/ demos/08.js
const logger = (ctx, next) => {
console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`);
next();
}
app.use(logger);
像上面代码中的logger函数就叫做"中间件"(middleware),因为它处在 HTTP Request 和 HTTP Response 中间,用来实现某种中间功能。
app.use()用来加载中间件。
基本上,Koa 所有的功能都是通过中间件实现的,前面例子里面的main也是中间件。
每个中间件默认接受两个参数,第一个参数是 Context 对象,第二个参数是next函数。只要调用next函数,就可以把执行权转交给下一个中间件。
ctx代表 Context 对象,表示一次对话的上下文(包括 HTTP 请求和 HTTP 回复)。通过加工这个对象,就可以控制返回给用户的内容。
运行这个 demo。
$ node demos/08.js
访问 http://127.0.0.1:3000 ,命令行窗口会显示与上一个例子相同的日志输出。
3.3 中间件栈
多个中间件会形成一个栈结构(middle stack),以"先进后出"(first-in-last-out)的顺序执行。
最外层的中间件首先执行。
调用next函数,把执行权交给下一个中间件。
...
最内层的中间件最后执行。
执行结束后,把执行权交回上一层的中间件。
...
最外层的中间件收回执行权之后,执行next函数后面的代码。
// demos/09.js
const one = (ctx, next) => {
console.log('>> one');
next();
console.log('<< one');
}
const two = (ctx, next) => {
console.log('>> two');
next();
console.log('<< two');
}
const three = (ctx, next) => {
console.log('>> three');
next();
console.log('<< three');
}
app.use(one);
app.use(two);
app.use(three);
运行这个demo
$ node demos/09.js
访问 http://127.0.0.1:3000 ,命令行窗口会有如下输出。
>> one
>> two
>> three
<< three
<< two
<< one
如果中间件内部没有调用next函数,那么执行权就不会传递下去。
3.4 异步中间件
迄今为止,所有例子的中间件都是同步的,不包含异步操作。如果有异步操作(比如读取数据库),中间件就必须写成 async 函数。
// demos/10.js
const fs = require('fs.promised');
const Koa = require('koa');
const app = new Koa();
const main = async function (ctx, next) {
ctx.response.type = 'html';
ctx.response.body = await fs.readFile('./demos/template.html', 'utf8');
};
app.use(main);
app.listen(3000);
上面代码中,**fs.readFile**是一个异步操作,必须写成**await fs.readFile()**,然后**中间件必须写成 async 函数。**
运行这个 demo。
$ node demos/10.js
访问 http://127.0.0.1:3000 ,就可以看到模板文件的内容。
3.5 中间件的合成
koa-compose模块可以将多个中间件合成为一个。
// demos/11.js
const compose = require('koa-compose');
const logger = (ctx, next) => {
console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`);
next();
}
const main = ctx => {
ctx.response.body = 'Hello World';
};
const middlewares = compose([logger, main]);
app.use(middlewares);
运行这个demo
$ node demos/11.js
访问 http://127.0.0.1:3000 ,就可以在命令行窗口看到日志信息。