-
koa2 进阶学习笔记
-
1.1 快速开始
-
1.2 async/await使用
-
1.3 koa2简析结构
-
1.4 koa中间件开发与使用
-
2.1 原生koa2实现路由
-
2.2 koa-router中间件
-
3.1 GET请求数据获取
-
3.2 POST请求数据获取
-
3.3 koa-bodyparser中间件
-
4.1 原生koa2实现静态资源服务器
-
4.2 koa-static中间件
-
5.1 koa2使用cookie
-
5.2 koa2实现session
-
6.1 koa2加载模板引擎
-
6.2 ejs模板引擎
-
7.1 busboy模块
-
7.2 上传文件简单实现
-
7.3 异步上传图片实现
-
8.1 mysql模块
-
8.2 async/await封装使用mysql
-
8.3 项目建表初始化
-
9.1 原生koa2实现JSONP
-
9.2 koa-jsonp中间件
-
10.1 单元测试
-
11.1 开发debug
-
12.1 快速启动
-
12.2 框架设计
-
12.3 分层操作
-
12.4 数据库设计
-
12.5 路由设计
-
12.6 webpack4环境搭建
-
12.7 使用react.js
-
12.8 登录注册功能实现
-
12.9 session登录态判断处理
-
13.1 import/export使用
-
1.1 快速开始
koa中间件开发和使用
注:原文地址在我的博客issue里https://github.com/ChenShenhai/blog/issues/15
- koa v1和v2中使用到的中间件的开发和使用
- generator 中间件开发在koa v1和v2中使用
- async await 中间件开发和只能在koa v2中使用
generator中间件开发
generator中间件开发
generator中间件返回的应该是function * () 函数
/* ./middleware/logger-generator.js */
function log( ctx ) {
console.log( ctx.method, ctx.header.host + ctx.url )
}
module.exports = function () {
return function * ( next ) {
// 执行中间件的操作
log( this )
if ( next ) {
yield next
}
}
}
copy
generator中间件在koa@1中的使用
generator 中间件在koa v1中可以直接use使用
const koa = require('koa') // koa v1
const loggerGenerator = require('./middleware/logger-generator')
const app = koa()
app.use(loggerGenerator())
app.use(function *( ) {
this.body = 'hello world!'
})
app.listen(3000)
console.log('the server is starting at port 3000')
copy
generator中间件在koa@2中的使用
generator 中间件在koa v2中需要用koa-convert封装一下才能使用
const Koa = require('koa') // koa v2
const convert = require('koa-convert')
const loggerGenerator = require('./middleware/logger-generator')
const app = new Koa()
app.use(convert(loggerGenerator()))
app.use(( ctx ) => {
ctx.body = 'hello world!'
})
app.listen(3000)
console.log('the server is starting at port 3000')
copy
async中间件开发
async 中间件开发
/* ./middleware/logger-async.js */
function log( ctx ) {
console.log( ctx.method, ctx.header.host + ctx.url )
}
module.exports = function () {
return async function ( ctx, next ) {
log(ctx);
await next()
}
}
copy
async 中间件在koa@2中使用
async 中间件只能在 koa v2中使用
const Koa = require('koa') // koa v2
const loggerAsync = require('./middleware/logger-async')
const app = new Koa()
app.use(loggerAsync())
app.use(( ctx ) => {
ctx.body = 'hello world!'
})
app.listen(3000)
console.log('the server is starting at port 3000')
copy