系列文章目录
一阶段
1.Node基本模块之 fs
2. Node基本模块之stream
3.Node基本模块之http
4.Node基本模块之crypto
二阶段 koa框架
1.koa入门以及koal
2.koa的模板引擎Nunjucks
3.koa实现MVC模式
三阶段
1.Node+WebSocket 实现一个聊天室
四阶段
1.在koa中如何使用REST
2.在koa中编写符合REST 的接口
文章目录
- 系列文章目录
- 前言
- 一、.koa是什么?
- 二、middleware
- 三、koa-router
- 总结
前言
一、.koa是什么?
- koa是Express的下一代基于Node.js的web框架,目前有1.x和2.0两个版本,我们这里学习的是2.0版本,其实1.x和2.0最大的区别就是实现异步的方式,koa 1.0使用generator实现异步,2.0则是使用promis结合async await 实现异步。
二、middleware
- 导入koa,和koa 1.x不同,在koa2中,我们导入的是一个class,因此用大写的Koa表示。
- 创建服务
- 监听端口
代码如下(示例):
javascript">const Koa = require('koa');
const app = new Koa();
app.use(async(ctx, next) => {
await next();
ctx.response.type = 'text/html';
ctx.response.body = '<h1>Hello, koa2!</h1>';
});
app.listen(3000);
console.log('app started at port 3000...');
koa的核心执行逻辑分析:
javascript">app.use(async(ctx, next) => {
await next();
ctx.response.type = 'text/html';
ctx.response.body = '<h1>Hello, koa2!</h1>';
});
- 每收到一个http请求,koa就会调用通过app.use()注册的async函数,并传入ctx和next参数。我们可以对ctx进行操作,来设置response返回的内容。
- await next()的作用是:koa把很多async函数组成一个处理链,每个async函数都可以做一些自己的事情,然后用await next()来调用下一个async函数。我们把每个async函数称为middleware,这些middleware可以组合起来,完成很多有用的功能
- middleware的顺序很重要,也就是调用app.use()的顺序决定了middleware的顺序。
- 如果一个middleware没有调用await next(),后续的middleware将不再执行了
我们可以创建多个middleware,如下:
javascript">app.use(async(ctx, next) => {
console.log(`${ctx.request.method} ${ctx.request.url}`); // 打印URL
console.log('第一个middleware')
await next(); // 调用下一个middleware
});
app.use(async(ctx, next) => {
const start = new Date().getTime(); // 当前时间
await next(); // 调用下一个middleware
const ms = new Date().getTime() - start; // 耗费时间
console.log(`Time: ${ms}ms`); // 打印耗费时间
console.log('第二个middleware')
});
app.use(async(ctx, next) => {
await next();
ctx.response.type = 'text/html';
ctx.response.body = '<h1>Hello, koa2!</h1>';
console.log('第三个middleware')
});
三、koa-router
koa-router作用:
- 为了处理不同的url,我们需要引入koa-router,koa-router可以处理不同url的映射,我们需要安装koa-router。
koa-router使用方法:
- 1.npm install middleware --save
- 2.引入 const router = require(‘koa-router’)();
- 3.使用 app.use(router.routes());
javascript">const Koa = require('koa');
// 注意require('koa-router')返回的是函数:
const router = require('koa-router')();
router.get('/', async(ctx, next) => {
ctx.response.body = '<h1>Index</h1>';
});
router.get('/home', async(ctx, next) => {
ctx.response.body = '<h1>这是首页</h1>';
});
router.get('/pages', async(ctx, next) => {
ctx.response.body = '<h1>这是其他页面</h1>';
});
//使用
app.use(router.routes());
app.listen(3000);
koa-router 对post请求的支持:
- post请求通常会发送一个表单,或者JSON,它作为request的body发送,但无论是Node.js提供的原始request对象,还是koa提供的request对象
- npm install koa-bodyparser --save
javascript">//引入
const bodyParser = require('koa-bodyparser');
router.post('/signin', async(ctx, next) => {
var
name = ctx.request.body.name || '',
password = ctx.request.body.password || '';
console.log(`signin with name: ${name}, password: ${password}`);
if (name === 'koa' && password === '12345') {
ctx.response.body = `<h1>Welcome, ${name}!</h1>`;
} else {
ctx.response.body = `<h1>Login failed!</h1>
<p><a href="/">Try again</a></p>`;
}
});
//使用
app.use(bodyParser());
总结
这篇文章主要学习koa框架一些基础的知识点,简单的koa服务创建,以及利用koa-router映射地址,根据不同的path返回不同的数据。