koa-bodyparser獲取post參數

1.不使用koa-bodyparser獲取post參數
router.post('/postData',async (ctx,next)=>{
	let postData="";                    // 用於存儲post的數據
	ctx.req.on('data',function(data){
    postData+=data;                     // 將數據拼接起來
    })
	ctx.req.on('end',function(){
    	console.log(postData);          // 獲取數據
    	ctx.res.end('')
	})
	await next();
})
2. 使用bodyparser() 獲取參數
2.1 安裝
npm i koa-bodyparser
2.2 導入
const bodyparser=require('koa-bodyparser');
app.use(bodyparser());
2.3 獲取參數
router.post('/postData',async (ctx,next)=>{
	ctx.body=ctx.request.body;         // post的參數存在ctx.request.body中
	console.log(ctx.request.rawBody);  // 存放沒有處理過的post數據
})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章