1.安装
npm install koa-bodyparser --save
2.引入
// 引入koa-bodyparser插件
let bodyparser = require('koa-bodyparser');
3.配置
// 配置中间件
app.use(bodyparser());
4.使用
ctx.request.body;//获取post传过来的参数
案例:
app_post.js
let Koa = require('koa');
let Router = require('koa-router');
let views = require('koa-views');
let app = new Koa();
let router = new Router();
let path = require('path');
// 引入koa-bodyparser插件
let bodyparser = require('koa-bodyparser');
// 配置中间件
app.use(bodyparser());
//应用ejs模板引擎
app.use(views('views',{
extension:'ejs'
}))
router.get('/',async (ctx,next) => {
// ctx.body = '这是首页'
await ctx.render('post')
})
router.post('/doPost',async (ctx,next) => {
ctx.body = ctx.request.body;//获取post传过来的参数
})
app.use(router.routes());//启动路由
app.use(router.allowedMethods());
app.listen(3004);
views/post.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="/css/basic.css">
</head>
<body>
<form action="/doPost" method="post">
<input type="text" placeholder="请输入用户名" name='username'>
<br>
<input type="password" placeholder="请输入密码" name='psd'>
<br>
<button class="btn" type="submit">提交</button>
</form>
</body>
</html>