GET格式参数接收
const router = require('koa-router')()
router.prefix('/api')
router.get("/list",,async (ctx)=>{
let query = ctx.puery
console.log("参数接收",query)
ctx.body = {
code:101,
data:[
{name:'zhangsan',age:18},
{name:'wangwu',,age:19}
]
}
})
module.exports = router
POST格式接收(支持JSON \ form-data \ x-www-form-urlencoded )
在 app.js 文件中配置如下
const bodyparser = require('koa-body')
app.use(bodyparser({
enableTypes:['json', 'form', 'text'],
multipart:true
}))
安装
npm install koa-body --save
在路由中使用
const router = require('koa-router')()
router.prefix('/api')
router.post("/create", async (ctx)=>{
let body = ctx.request.body;
console.log("打印post参数",body)
ctx.body="hello world"
})
module.exports = router
接收文件上传
配置同POST方式一样,语法同上
const fs = require("fs")
const path = require("path")
const router = require('koa-router')()
router.prefix('/api')
router.post("/create", async (ctx)=>{
let body = ctx.request.body;
console.log("额外的文件参数")
const file = ctx.request.files.file; // 获取上传文件
// 创建可读流
const reader = fs.createReadStream(file.path);
let filePath = path.join(__dirname, 'public/upload/') + `/${file.name}`;
console.log(filePath)
// 创建可写流
const upStream = fs.createWriteStream(filePath);
// 可读流通过管道写入可写流
reader.pipe(upStream);
return ctx.body = "上传成功!";
})
module.exports = router