koa 中获取 post 提交数据
原生 NodeJS 获取 post 提交的数据
request.js
exports.getPostData=function(ctx){ return new Promise((resolve,reject)=>{ try { let params = ''; ctx.req.on('data', (chunk) => { params += chunk; }) ctx.req.on('end', (chunk) => { resolve(params) }) } catch (error) { console.log("获取post提交的数据错误") reject(error) } }) }
app.js
const Koa = require('koa') const app = new Koa() const router = require('koa-router')() const views = require('koa-views') const ejs = require('ejs') const request = require('./utils/request') //应用ejs模板引擎 app.use(views('views',{ extension:'ejs' })) router.get('/register',async (ctx)=>{ console.log("注册页") await ctx.render('register') }) router.post('/doRegister',async (ctx)=>{ let data = await request.getPostData(ctx) console.log("注册页提交的数据是:", data) //userName=admin&password=123 ctx.body=data }) app.use(router.routes()); app.use(router.allowedMethods()); app.listen(3000);
使用 koa-bodyparser 中间件获取提交数据
https://www.npmjs.com/package/koa-bodyparser
npm install --save koa-bodyparser
const Koa = require('koa') const app = new Koa() const router = require('koa-router')() const views = require('koa-views') const ejs = require('ejs') const bodyParser = require('koa-bodyparser') //应用ejs模板引擎 app.use(views('views',{ extension:'ejs' })) //配置 bodyParsey中间件 app.use(bodyParser()) router.get('/register',async (ctx)=>{ console.log("注册页") await ctx.render('register') }) router.post('/doRegister',async (ctx)=>{ let data = ctx.request.body console.log("注册页提交的数据是:", data) //{"userName":"admin","password":"123"} ctx.body=data }) app.use(router.routes()); app.use(router.allowedMethods()); app.listen(3000);