1.app.js
// 引入模块 const Koa = require('koa'); const router = require('koa-router')(); /*引入是实例化路由 推荐*/ const views = require('koa-views'); const common = require('./module/common.js'); // 实例化 let app = new Koa(); // 应用ejs模板引擎 app.use(views('views', { map: { html: 'ejs' } })); router.get('/', async (ctx) => { await ctx.render('index'); }) // 接收post提交的数据 router.post('/doAdd', async (ctx) => { // 原生node.js 在 koa 中获取表单提交的数据 let data = await common.getPostData(ctx); console.log(data); ctx.body = data; }) app.use(router.routes()); app.use(router.allowedMethods()); app.listen(3000);
2.module/common.js
exports.getPostData = function (ctx) { // 获取数据 异步 return new Promise(function (resolve, reject) { try { let str = ''; ctx.req.on('data', function (chunk) { str += chunk; }) ctx.req.on('end', function (chunk) { resolve(str) }) } catch (err) { reject(err); } }) }
3.index.html
<!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> </head> <body> <form action="/doAdd" method="post"> 用户名:<input type="text" name="username" /> <br /> 密码: <input type="password" name="password" /> <br /> <button type="submit">提交</button> </form> </body> </html>
4.目录
5.效果图