一、获取动态路径参数
发送请求:
http://localhost:3000/v1/3/classic/latest
需要获取到里面的 3
接收请求
// 1. 获取路径里面的 id
router.post('/v1/:id/classic/latest', async ctx => {
const id = ctx.params.id
console.log(path)
ctx.body = {key: 'calssic'}
})
二、获取获取解析的查询字符串
发送请求:
http://localhost:3000/v1/3/classic/latest?param=duck
接收请求
// 2. 获取解析的查询字符串
router.post('/v1/:id/classic/latest', async ctx => {
// 获取到一个对象,如果为空,则为空对象
const query = ctx.request.query
console.log(query)
ctx.body = {key: 'calssic'}
})
三、获取头部信息
发送请求:
http://localhost:3000/v1/3/classic/latest
头部:token: 123123123
接收请求
// 3. 获取头部信息
router.post('/v1/:id/classic/latest', async ctx => {
const headers = ctx.request.header
console.log(headers.token)
ctx.body = {key: 'calssic'}
})
四、获取POST信息
发送请求:
http://localhost:3000/v1/3/classic/latest
body: key: pig
接收请求:
- 安装依赖
koa-bodyparser
npm install koa-bodyparser --save
- 在主文件引入并注册
// 引入模块
const parser = require('koa-bodyparser')
// 注册
app.use(parser())
- 使用并获取参数
// 3. 获取body信息
router.post('/v1/:id/classic/latest', async ctx => {
const body = ctx.request.body
console.log(body.key)
ctx.body = {key: 'calssic'}
})