koa获取get和post的参数实例代码
2024-09-08 18:29:42
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 打开
最新文章
- W3Help-兼容性-知识库
- 保留password模式文本框textbox内的数据不丢失。
- 【ASP.NET】利用Nuget打包package——GUI方式
- 关于linux curl 地址参数的问题
- Web Design - The Viewport
- Ubuntu添加开机自动启动程序的方法
- Maven+Spring+Hibernate+Shiro+Mysql简单的demo框架(一)
- ios开发——实用技术OC篇》倒计时实现的两种方法
- c# DateTime时间格式和JAVA时间戳格式相互转换
- 反编译c#的相关问题
- 类库探源——System.Drawing
- Linux终端Ctrl相关快捷键
- servlet第3讲(上集)----同一用户的不同页面共享数据
- H5微信播放全屏问题
- sublime snippet 示例
- Unity shader学习之屏幕后期处理效果之高度雾,重建world pos方法2
- Fish 下报错 Unsupported use of '||'. In fish, please use 'COMMAND; or COMMAND'.
- 【LOJ#6277】数列分块1
- android开发(33) 让 actionbar 透明2
- 今天踩过的坑——structs和mysql