3. Koa2 处理 http 请求
- 返回字符串格式:
ctx 即 res 和 req 的集合
const router = require('koa-router')()
router.prefix('/api') // 前缀
// 定义路由:模拟获取留言板列表
router.get('/list', async (ctx) => {
const query = ctx.query // req 功能
console.log('query', query)
ctx.body = 'api list' // res 功能(返回字符串格式)
})
// 定义路由:模拟创建留言内容
router.post('/create', async (ctx) => {
const body = ctx.request.body // request body
console.log('body', body)
ctx.body = 'api create'
})
module.exports = router // 输出
-
get 请求
输入 http://localhost:3000/api/list?a=100&b=200
控制台返回: { a: ‘100’, b: ‘200’ }
-
post 请求
postman 中输入 http://localhost:3000/api/create
body raw 下输入{ “content”: “新留言的内容”,“user”: “zhangsan”} //JSON
send 后:控制台返回 { “content”: “新留言的内容”,“user”: “zhangsan”}
-
返回 JSON 格式
ctx.body = { errno: 0, data: [ { content: '留言1', user: '张三' }, { content: '留言2', user: '李四' }, { content: '留言3', user: '王二' }, ] }