koa post 提交数据 koa-bodyparser 中间件的使用
原生的node ejs实现post数据获取
// app.js
const Koa = require('koa')
const Router = require('koa-router')
const views = require('koa-views')
const common = require('./module/common')
const app = new Koa()
const router = new Router()
app.use(views('html', {
extension: 'ejs'
}))
router.get('/', async (ctx) => {
await ctx.render('post')
})
router.post('/doAdd', async (ctx) => {
let data = await common.getPostData(ctx)
ctx.body = data
})
app.use(router.routes())
.use(router.allowedMethods())
app.listen(30001)
// post.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>
密 码:<input type="password" name="password">
<br>
<button type="submit">提交</button>
</form>
</body>
</html>
// common.js
exports.getPostData = function (ctx) {
return new Promise((resolve, reject) => {
try {
let str = ''
ctx.req.on('data', (chunk) => {
str += chunk
})
ctx.req.on('end', (chunk) => {
resolve(str)
})
} catch (error) {
reject(error)
}
})
}
koa-bodyparser中间件实现数据提交
// 安装
npm install --save koa-bodyparser
app.js
const Koa = require('koa')
const Router = require('koa-router')
const views = require('koa-views')
const bodyParser = require('koa-bodyparser')
const app = new Koa()
const router = new Router()
app.use(views('html', {
extension: 'ejs'
}))
app.use(bodyParser())
router.get('/', async (ctx) => {
await ctx.render('post')
})
router.post('/doAdd', async (ctx) => {
ctx.body = ctx.request.body
})
app.use(router.routes())
.use(router.allowedMethods())
app.listen(30001)
效果截图