koa获取get和post的参数实例代码


 1 const Koa = require('koa');
 2 const Router = require('koa-router');//引用koa-router
 3 const KoaBody = require('koa-body');
 4 //引用内部数据结构
 5 
 6 //
 7 const app = new Koa();
 8 app.use(KoaBody());
 9 
10 const router = new Router();//创建路由。支持传递参数
11 //response
12 app.use(async (ctx, next) => {
13   ctx.body = 'Hello koa';
14   next();
15 });
16 
17 router.get("/", async (ctx) => {
18   //请求的地址,带参数的路由地址
19   console.log(ctx.url)
20   //url参数 使用的是 ctx.query
21   console.log(ctx.query);
22   //console.log(ctx.querystring);
23 })
24 
25 //postman
26 router.post("/a", async ctx => {
27   console.log(ctx.url);//获取请求地址
28   console.log(ctx.request.body);//获取参数
29   ctx.body="请求成功"
30 });
31 
32 // 调用router.routes()来组装匹配好的路由,返回一个合并好的中间件
33 // 调用router.allowedMethods()获得一个中间件,当发送了不符合的请求时,会返回 `405 Method Not Allowed` 或 `501 Not Implemented`
34 app.use(router.routes()).use(router.allowedMethods());
35 //localhost:3000
36 app.listen(3000, () => {
37   console.log("http://localhost:3000");
38 });

建一个文件:“test.http”

 1 POST http://localhost:3000/a
 2 Content-Type: application/json
 3 
 4 #content
 5 //表单方式
 6 #id=1000&name="张三"
 7 {
 8     "id":1000,
 9    "name":"张三"
10 }

nodemon app.js  打开