一起来探索Koa的奥秘
To explore Koa
上篇我们介绍了Koa2这个框架以及基础的服务搭建,接下来学习Koa2的中间件以及路由。Koa2在介绍中也提到了,它不内置中间件,但是提供中间件内核。中间件是Koa2的核心。
Koa中间件
中间件是什么?
koa2的中间件是通过 async await
实现的,中间件执行顺序是“洋葱圈”模型。
中间件之间通过next函数联系,当一个中间件调用 next()
后,会将控制权交给下一个中间件, 直到下一个中间件不再执行 next()
后, 将会沿路折返,将控制权依次交换给前一个中间件。
// 洋葱模型特点
// 引入 Koa
const Koa = require("koa");
// 创建服务
const app = new Koa();
app.use(async (ctx, next) => {
console.log(1);
await next();
console.log(2);
});
app.use(async (ctx, next) => {
console.log(3);
await next();
console.log(4);
});
app.use(async (ctx, next) => {
console.log(5);
await next();
console.log(6);
});
// 监听服务
app.listen(3000, () => {
console.log('starting at port 3000')
})
// 执行结果
// 1
// 3
// 5
// 6
// 4
// 2
Koa路由
路由是什么?
路由(Routing)是由一个 URI(或者叫路径)和一个特定的 HTTP 方法(GET、POST 等)组成的,涉及到应用如何响应客户端对某个网站节点的访问。路由就是根据不同的URL地址,加载不同的页面实现不同的功能。PS:一般正常开发中,我们使用 koa-router 第三方中间件来开发,也可以自己封装路由中间件,也比较容易,但是重复造轮子是大忌,懂得原理即可
koa-router基本使用
前面介绍了中间件,在这我们使用koa-router中间件,首先在项目中安装koa-router
npm install --save koa-router
koa-router的使用
const Koa = require('koa')
const app = new Koa()
const Router = require('koa-router')
// 路由1
let home = new Router()
home.get('/', async ( ctx )=>{
ctx.body = "路由1"
})
// 路由2
let page = new Router()
page.get('/404', async ( ctx )=>{
ctx.body = '路由2 --> 404 page!'
}).get('/hello', async ( ctx )=>{
ctx.body = '路由2 --> helloworld page!'
})
// 装载所有子路由
let router = new Router()
router.use('/', home.routes(), home.allowedMethods())
router.use('/page', page.routes(), page.allowedMethods())
// 加载路由中间件
app.use(router.routes()).use(router.allowedMethods())
app.listen(3000, () => {
console.log('starting at port 3000')
})
node app.js运行
http://localhost:3000/页面会输出
http://localhost:3000/page/404页面会输出
http://localhost:3000/page/hello页面会输出
上面的代码分了2个路由模块,home路由模块和 page 路由模块,通过 2次 new Router() 实例化实现,再实例化一个总的路由集合router将所有子路由集合,最后通app.use(router.routes()).use(router.allowedMethods()) 方法将 路由集合router注册在整个服务程序中
koa路由get传值
在koa2中GET传值通过request接收,但是接收的方法有两种:query和querystring。
query:返回的是格式化好的参数对象。
querystring:返回的是请求字符串。
const Koa = require('koa')
const app = new Koa()
const Router = require('koa-router')
let router = new Router()
router.get('/', function (ctx, next) {
ctx.body = "Hello World";
})
router.get('/getParam', async (ctx) => {
let url = ctx.url;
//从request中获取GET请求
let request = ctx.request;
let req_query = request.query;
let req_querystring = request.querystring;
//从上下文中直接获取
let ctx_query = ctx.query;
let ctx_querystring = ctx.querystring;
ctx.body = {
url, // "getparam?id=123"
req_query, // {"123":"123"}
req_querystring, // "id=123"
ctx_query, // {"id":123}}
ctx_querystring // "id=123"
}
// {
// "url":"/getParam?id=123",
// "req_query":{"id":"123"},
// "req_querystring":"id=123",
// "ctx_query":{"id":"123"},
// "ctx_querystring":"id=123"
// }
})
// 加载路由中间件
app.use(router.routes()).use(router.allowedMethods())
app.listen(3000, () => {
console.log('starting at port 3000')
})
koa动态路由
ctx.params:获取动态路由传参
const Koa = require('koa')
const app = new Koa()
const Router = require('koa-router')
let router = new Router()
router.get('/', function (ctx, next) {
ctx.body = "Hello World";
})
router.get('/getParam/:id', async (ctx) => {
//ctx.params获取动态路由传参
console.log(ctx.params) // {"id":"123"}
ctx.body= ctx.params;
})
// 加载路由中间件
app.use(router.routes()).use(router.allowedMethods())
app.listen(3000, () => {
console.log('starting at port 3000')
})
—— 敬请期待 ——
公众号 : 码个球