4-1 控制器简介
- 获取HTTP请求参数
- 处理业务逻辑
- 发送HTTP响应
获取 HTTP 请求参数
- Query String,如?q= keyword
- Router Params,如/users/:id
- Body(请求体),如{name: “李雷”},注意不止是json格式还有form格式,通过content-type区分发送。
- Header(请求头),如Accept、Cookie
发送 HTTP 响应
- 发送 Status,如200/400
- 发送 Body,如{name: '李雷‘}
- 发送 Header,如 Allow,Content-Type
4-2 获取HTTP 请求参数
npm i koa-bodyparser --save
const bodyparser = require('koa-bodyparser')
app.use(bodyparser())
4-3 发送HTTP响应
- 发送 status ctx.status = 200
- 发送 body ctx.body = []
- 发送 header
usersRouter.get('/', (ctx) => {
ctx.set('Allow', 'GET, POST')
ctx.body =[{name: '李雷'}, {name: '韩梅梅'}]
})
模拟增删改查
内存数据库:
const db = [{name: '李雷'}]
查:
usersRouter.get('/', (ctx) => {
ctx.body = db
})
增:
usersRouter.post('/', (ctx) => {
db.push(ctx.request.body)
ctx.body = ctx.request.body
})
查特定用户:
usersRouter.put('/:id', (ctx) => {
ctx.body = db[ctx.params.id * 1]
})
修改用户:
usersRouter.put('/:id', (ctx) => {
db[ctx.params.id * 1] = ctx.request.body
ctx.body = ctx.request.body
})
删除用户:
usersRouter.delete('/:id', (ctx) => {
db.splice(ctx.params.id * 1, 1)
ctx.status = 204
})
4-4 更合理的目录结构
- 将路由单独放在一个目录
- 将控制器单独放在一个目录
- 使用 类+ 类方法的方式组织控制器
app/index.js
const koa = require('koa')
const bodyparser = require('koa-bodyparser')
const app = new koa()
const routing = require('./routes')
app.use(bodyparser())
routing(app)
app.listen(3000, () => console.log('程序启动在 3000 端口了'))
在app/index.js中实例化koa,引入路由并通过routing(app)注册路由,开启监听端口。
app/routes/index.js
const fs = require('fs')
module.exports = (app) => {
fs.readdirSync(__dirname).forEach(file => {
if (file === 'index.js') {
return
}
const route = require(`./${file}`)
app.use(route.routes()).use(route.allowedMethods())
})
}
此js导出为一个方法,在app/index.js中被引入使用,把所有路由都注册。
app/routes/home.js
const Router = require('koa-router')
const router = new Router()
const {index} = require('../controllers/home')
router.get('/', index)
module.exports = router
app/controllers/home.js
class HomeCtl {
index (ctx) {
ctx.body = '<h1>这是主页</h1>'
}
}
module.exports = new HomeCtl()
在router/home.js中引入了koa-router并实例化路由,编写路由并引入controller/home的方法作为路由的方法。
app/routes/users.js
const Router = require('koa-router')
const { prefix } = require('./home')
const router = new Router({prefix: '/users'})
const {find, findById, create, update, delete: del} = require('../controllers/users')
router.get('/', find)
router.post('/', create)
router.get('/:id', findById)
router.put('/:id', update)
router.delete('/:id', del)
module.exports = router
app/controllers/users.js
const db = [{name: '李雷'}]
class UsersCtl {
find (ctx) {
ctx.body = db
}
findById (ctx) {
ctx.body = db[ctx.params.id * 1]
}
create (ctx) {
db.push(ctx.request.body)
ctx.body = ctx.request.body
}
update (ctx) {
db[ctx.params.id * 1] = ctx.request.body
ctx.body = ctx.request.body
}
delete (ctx) {
db.splice(ctx.params.id * 1, 1)
ctx.status = 204
}
}
module.exports = new UsersCtl