get与post有三种传参方式
- 传统方式,通过“?=&”传递参数
- 通过路径传参
- post body传参
&传参
localhost:3000/home?id=3&user=me
通过 ctx.request.query 获取参数对象
通过 ctx.request.querystring 获取参数字符串
router.get('/home', async(ctx, next) => {
console.log(ctx.request.query) //对象
console.log(ctx.request.querystring) //字符串
ctx.response.body = '<h1>HOME page'+ctx.request.query.id +':'+ctx.request.query.user+'</h1>'
})
’ / ‘传参
localhost:3000/home/3/me
通过 ctx.params 获取参数对象
router.get('/home/:id/:user', async(ctx, next)=>{
console.log(ctx.params)
ctx.response.body = '<h1>HOME page '+ctx.params.id+':'+ctx.params.user+'</h1>'
})
post传参
post传值需要用到中间件 koa-bodyparser
koa-bodyparser使用
npm install koa-bodyparser
引用
const bodyParser = require('koa-bodyparser')
const app = new Koa()
app.use(bodyParser())
实例
通过ctx.request.body获取参数对象
router.get('/user', async(ctx, next)=>{
ctx.response.body =
`
<form action="/user/register" method="post">
<input name="name" type="text" placeholder="请输入用户名:ikcamp"/>
<br/>
<input name="password" type="text" placeholder="请输入密码:123456"/>
<br/>
<button>GoGoGo</button>
</form>
`
})
// 增加响应表单请求的路由
router.post('/user/register',async(ctx, next)=>{
let {name, password} = ctx.request.body
if( name == 'ikcamp' && password == '123456' ){
ctx.response.body = `Hello, ${name}!`
}else{
ctx.response.body = '账号信息错误'
}
})