- ctx是res和req的集合
- get方法中
ctx.body = 'api list' // 返回的内容即res功能
const query = ctx.query // 获取req,即querystring
console.log('query', query);
浏览器中输入querystring,看看console出来的内容
完整代码:
// 定义路由,模拟获取留言版列表,ctx是res和req的集合
router.get('/list', async(ctx) => { // router地址为 /api/list
ctx.body = 'api list' // 返回的内容即res
const query = ctx.query // 获取req,即querystring
console.log('query', query);
})
- post方法中,获取request body
const body = ctx.request.body // 获取request body
console.log('body', body)
用postman模拟POST请求,看控制台的打印结果
完整代码:
// 定义路由:模拟创建留言
router.post('/create', async(ctx) => {
const body = ctx.request.body // 获取request body
console.log('body', body)
ctx.body = {
errorno:0,
message: '成功'
}
})
- 如果想返回json格式,直接返回即可,例如:
// 定义路由,模拟获取留言版列表,ctx是res和req的集合
router.get('/list', async(ctx) => { // router地址为 /api/list
const query = ctx.query // 获取req,即querystring
ctx.body = {
errorno: 0,
data: [
{content:'留言1', user: '张三'},
{content: '留言2', user: '李四'},
{content: '留言2', user: '王二'}
]
} // 返回的内容即res
console.log('query', query);
})