目录
koa2简介
koa2通过ES7 中的 async 和 await 来使异步请求写起来变得像同步
- 服务器每次收到http请求 就会执行app.use()注册中的async函数 并且传入ctx next参数
- Koa ctx 将 node 的 request 和 response 对象封装到单个对象中
- koa把很多async函数(middleware中间件)组成一个处理链
- 每个函数(middleware中间件)从上往下依次执行处理不同的功能
- 然后调用 await next()执行下一个函数(middleware中间件)
ctx.response.type = 设置响应 Content-Type 通过 mime 字符串或文件扩展名。
ctx.type = 'text/plain; charset=utf-8';
ctx.type = 'image/png';
ctx.type = '.png';
ctx.type = 'png';
response.body= 将响应体设置为以下之一:
string 写入
Buffer 写入
Stream 管道
Object || Array JSON-字符串化
null 无内容响应
koa2创建服务器
app.js文件
const Koa2 = require('koa')
const app = new Koa2()
// koa middleware中间件
app.use(async (ctx, next)=>{
await next()
console.log(ctx.request.url)
})
app.use(async (ctx, next)=>{
await next()
//设置响应类型
ctx.response.type = 'text/html'
//设置响应主体
ctx.response.body = '<h1>hollo koa2</h1>'
})
app.listen(3000)
console.log('node-koa2-app 运行在prot 3000')
实现路由
引入koa-router 通过 npm install koa-router 安装此依赖
简单的路由例子:
const Koa2 = require('koa')
// 引入koa-router 通过 npm install koa-router 安装此依赖
const router = require('koa-router')()
const app = new Koa2()
// koa middleware中间件
app.use(async (ctx, next)=>{
await next()
console.log('url路径:' + ctx.request.url)
})
// 指定一个url匹配
router.get('/', async (ctx, next) => {
ctx.type = 'html';
ctx.body = '<h1>hello world!</h1>';
})
router.get('/hello/:name', async (ctx, next) => {
var name = ctx.params.name;
ctx.response.body = `<h1>Hello, ${name}!</h1>`;
});
//注册路由到app上
app.use(router.routes());
app.listen(3000)
console.log('node-koa2-app 运行在prot 3000')
路由模块化
文件目录
执行顺序:
app.js → controller.js → 遍历controller文件夹查找.js → 匹配路径执行不同方法
app.js
注意:post请求时会发送一个表单,或者JSON,它作为request的body发送。但是nodejs还是koa提供的 request对象 都不提供解析request的body功能需要通过 npm install koa-bodyparser 安装此依赖然后,引入koa-bodyparser 在注册app.use(bodyparser())
const Koa2 = require('koa')
const controller = require('./controller')
//引入koa-bodyparser
const bodyparser = require('koa-bodyparser')
const app = new Koa2()
// 注册处理request对象的中间件
app.use(bodyparser())
// koa middleware中间件
app.use(async (ctx, next)=>{
await next()
console.log('url路径:' + ctx.request.url)
})
//调用controller返回router.routes 注册到app上
app.use(controller());
app.listen(3000)
console.log('node-koa2-app 运行在prot 3000')
conteroller.js
// 引入koa-router 通过 npm install koa-router 安装此依赖
const router = require('koa-router')()
const fs = require('fs')
// 读取controller获取文件列表并查找.js文件控制器方法
let files = fs.readdirSync('./controller') //['index.js','hello.js']
let file_js = files.filter((item)=>{
return item.endsWith('.js')
})
//循环文件名数组
file_js.forEach((item,index)=>{
// 依次require引入 并判断请求方法 注册到router.get() || router.post()中
let pathHandler = require('./controller/' + item)
//获取对象键名
let keys = Object.keys(pathHandler)
keys.forEach((k)=>{
if(k.startsWith('GET ')){
let url = k.substring(4)
console.log(url)
router.get(url,pathHandler[k])
}else if(k.startsWith('POST ')){
let url = k.substring(5)
router.post(url,pathHandler[k])
}else{
console.log('没有url')
}
})
})
//将设置好的router输出
module.exports = ()=>{
return router.routes()
}
hello.js和index.js文件
//index.js
let index = async (ctx, next)=>{
//ctx.response.body = {name:'小明',age:12} //返回json数据
ctx.response.body = "<h1>hello</h1>"
}
//将对应路径和路由方法输出
module.exports = {
'GET /':index
}
//hello.js
let hello = async (ctx, next)=>{
let params = ctx.params
ctx.response.body = `<h1>hello,${params.name}</h1>
<form action="/api" method="post">
say:<input type="text" value="" name="message" />
<input type="submit" value="提交"/>
</form>
`
}
let ispost = async (ctx, next)=>{
console.log(ctx.request.body)
ctx.response.body = `<h1>hello,${ctx.request.body.message}</h1>`
}
//将对应路径和路由方法输出
module.exports = {
'GET /hello/:name':hello,
'POST /api':ispost,
}
koa返回HTML文件和静态文件处理
app.js
const Koa2 = require('koa')
const controller = require('./controller')
// 通过 npm install koa-static 安装此依赖
const staticFile = require('koa-static')
// 通过 npm install koa-bodyparser 安装此依赖
const bodyparser = require('koa-bodyparser')
const app = new Koa2()
// 注册处理request对象的中间件
app.use(bodyparser())
// 注册静态资源文件处理的中间件
app.use(staticFile(__dirname + '/'))
// koa middleware中间件
app.use(async (ctx, next)=>{
await next()
console.log('url路径:' + ctx.request.url)
})
//调用controller返回router.routes 注册到app上
app.use(controller());
app.listen(3000)
console.log('node-koa2-app 运行在prot 3000')
controller/index.js
const fs = require('fs')
let index = async (ctx, next)=>{
ctx.response.type = "text/html"
//这个不可用
// fs.createReadStream("./view/index.html",'utf8').pipe(ctx.body)
//读取文件并响应到浏览器
ctx.response.body = fs.readFileSync("./view/index.html")
}
//将对应路径和路由方法输出
module.exports = {
'GET /':index,
}