koa
koa 是基于 Node.js 的下一代 Web 框架。
简介
Koa 是一个新的 web 框架,由 Express 幕后的原班人马打造, 致力于成为 web 应用和 API 开发领域中的一个更小、更富有表现力、更健壮的基石。 通过利用 async 函数,Koa 帮你丢弃回调函数,并有力地增强错误处理。 Koa 并没有捆绑任何中间件, 而是提供了一套优雅的方法,帮助您快速而愉快地编写服务端应用程序。
安装
Koa 依赖 node v7.6.0 及其以上的版本
npm i koa -s
开始做一个 Hello World
如下的目录文件:
index.js
如下的代码:
const koa = require('koa');
const app = new koa();
app.use((ctx) => {
ctx.body = 'Hello World'
})
app.listen(3000);
OK,运行如下代码启动它:
node index.js
Async
在 koa 中很多代码使用了 async,所以我们需要了解 async 的用法
如果该函数是一个异步函数,可以使用 async
const fun = async () => {
const res = await fetch(/ 代码... /)
const json = await res.json();
console.log(json);
}
中间件
koa 的中间件其实是需要使用 next() 来调用的,它的中间件就是一个洋葱模型
路由
路由是什么
路由就是决定了不同URL是如何被不同地执行的。
那么在 Koa 中 ,路由其实是一个中间件
为什么要使用路由
如果没有路由,会怎么样?
- 所有请求都做了相同的事
- 所有请求都会返回相同的结果
路由存在的意义
- 处理不同的 URL
- 处理不同的 HTTP 方法
- 解析 URL 上的参数
- …
自己编写一个简单的 “路由” 中间件
const koa = require('koa');
const app = new koa();
app.use(async (ctx) => {
const {
url} = ctx;
if(url === '/') {
ctx.body = '这是主页';
} else if (ctx.url === '/users') {
if(ctx.method === 'GET') {
ctx.body = '这是用户列表页'
} else if (ctx.method === 'POST') {
ctx.body = '创建用户'
} else {
ctx.status = 405
}
} else if (url.match(/\/users\/\w+/)) {
const userId = url.match(/\/users\/(\w+)/)[1]
ctx.body = `这是用户 ${
userId}`
} else {
ctx.status = 404;
}
})
app.listen(3000);
使用 koa-router 实现路由
安装