1、app.js
var Koa = require(‘koa‘), router = require(‘koa-router‘)() views = require(‘koa-views‘) bodyParser = require(‘koa-bodyparser‘) var app = new Koa() //配置post bodyparser的中间件 app.use(bodyParser()) app.use(views(‘06_koa_post_bodyparser/views‘, { extension: ‘ejs‘ //应用ejs模板引擎 文件路径为06_koa_post_bodyparser/views,文件名为index.ejs })) router.get(‘/‘, async (ctx)=>{ await ctx.render(‘index‘) }) router.get(‘/news‘, async (ctx)=>{ ctx.body = ‘新闻页面‘ }) //接收post提交的数据 router.post(‘/doAdd‘, async (ctx)=>{ console.log(ctx.request.body) ctx.body = ctx.request.body //获取表单提交的数据 }) app.use(router.routes()) //启动路由 app.use(router.allowedMethods()) app.listen(3000)
2、index.ejs
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form action="/doAdd" method="post"> 用户名:<input type="text" name="username"/> </br> </br> 密 码:<input type="password" name="password"/> </br> </br> <button type="submit">提交</button> </form> </body> </html>