Koa项目搭建过程详细记录

2020-06-17 06:52:10易采站长站整理

路由控制

开发主要集中在路由控制这里,包括restful接口和模板渲染

获取参数(request)

查询参数(?param=a)


ctx.query.param

路由参数(/:id)


ctx.params.id

POST参数(JSON或Form)


ctx.request.body

请求回应(response)

服务器响应给客户端的数据

restful


ctx.body = yourData

模板渲染

默认从views目录开始,不许加文件后缀


ctx.render('layout', yourData)

路由拦截

未登录时拒绝请求,这样会返回404


const userAuth = (ctx, next) => {
let isLogin = ctx.session.isLogin
if(isLogin) return next()
}
router.use('/', userAuth)

此操作会包含在路由,如”/a”、”/b”等,需在子路由之前use,不然会无效