koa 是什么
Koa 是一个新的web 框架,由Express 幕后的原班人马打造, 致力于成为web 应用和API 开发领域中的一个更小、更富有表现力、更健壮的基石
洋葱模型
const Koa = require('koa') // 类名一般要大写
const app = new Koa() // 实例化
/*
* node 进程 如果没有重启的话 做得修改是没有用的
* */
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) => {
console.log(5)
})
app.listen(3000)
路由实现
- 原生
// 根据不同的url 路径 和 不同的请求方法 作出不同的响应
app.use(async (ctx, next) => {
if (ctx.url === '/') {
ctx.body = '这是主页'
} else if (ctx.url === '/users') {
if (ctx.method === 'GET') {
ctx.body = '这是用户列表页'
} else if (ctx.method === 'POST') {
ctx.set('Allow', 'GET, POST'); // 设置响应头
ctx.body = '创建用户'
}
} else {
ctx.status = 404
}
});
- koa-router
const Koa = require('koa'); // 类名一般要大写
const Router = require('koa-router');
const app = new Koa(); // 实例化
const router = new Router(); // 实例化
router.get('/', (ctx) => {
ctx.body = '这是主页';
});
router.get('/users', (ctx) => {
ctx.body = '这是用户列表';
});
router.get('/users/:id', (ctx) => {
ctx.body = `这是用户 ${ctx.pa