一、koa中间件
- 每收到一个http请求,koa就会调用通过app.use()注册的async函数,ctx封装了response和request,可以通过对ctx的操作,设置返回内容
- koa把很多async函数组成了一个处理链,每一个async函数都可以做自己的事情,然后通过await next()来调用下一个async函数,每一个async函数就是一个中间件,这些中间件可以组合起来,如果某一个中间件没有await next(),将不会再往下执行
- ctx的简写:ctx.url相当于ctx.request.url,ctx.type相当于ctx.response.type
const Koa = require("koa");
const app = new Koa();
app.use(async(ctx,next)=>{
ctx.response.type="text/html";
ctx.response.body="hello world"
await next()
})
// koa中间件,用来记录所有的请求及出现的错误,并且返回一个错误信息
app.use(async (ctx, next) => {
try {
console.log(`request with path ${ctx.path}`)
await next()
} catch (err) {
console.log(err)
ctx.status = 500
if (isDev) {
ctx.body = err.message
} else {
ctx.body = 'please try again later'
}
}
})
二、koa-router
根据不同的url,调用不同的处理函数,返回不同的结果(集中处理url的中间件
)
在这里插入代码片
三、koa-send
提供了一个封装非常完善的处理静态文件的中间件
const path = require('path')
const send = require('koa-send')
// 针对某个路径下的文件获取
router.get('/file', async ctx => {
await send(ctx, ctx.query.path, {
root: path.resolve(__dirname, './public')
})
})
// 针对某个文件的获取
router.get('/index', async ctx => {
await send(ctx, './public/index.log')
})
作者:贾顺名
链接:https://www.imooc.com/article/70719
来源:慕课网
问题:
server-render:koa-body
vue后端模板
koa+vue、express+vue(github)
webpack实现页面的按需加载
ctx