【Deno】m_oak_request_parser请求参数解析中间件

101 阅读1分钟

功能简介

一个基于oak通用的请求参数解析中间件

请求参数解析

get

get请求解析的参数最终会挂载到context的getParams参数上

import { Application, Router, Next, type BodyType, type BodyOptions } from "https://deno.land/x/oak@v12.5.0/mod.ts";
import RequestParser from 'https://deno.land/x/m_oak_request_parser/mod.js'
// import { getParser, bodyParser } from 'https://deno.land/x/m_oak_request_parser/mod.js'

const app = new Application();
const router = new Router();

app.use(RequestParser.getParser())

router.get("/upload", (ctx: any) => {
  const { name, age } = ctx['getParams']
  ctx.response.body = {
    name,
    age
  }
});

app.use(router.routes());
app.use(router.allowedMethods());

console.log('服务运行于: http://localhost:9000');
await app.listen({ port: 9000 });

post

post请求解析的参数最终会挂载到context的body参数上

json

post json

app.use(RequestParser.bodyParser())
ctx.response.body = ctx['body']
/* {
    "name": "mz",
    "obj": {
      "age": "19"
    }
}*/

urlencoded

post form-encode

app.use(RequestParser.bodyParser())
ctx.response.body = ctx['body']
/* {
    "name": "mz",
    "obj": {
      "age": "19"
    }
}*/

text

post text

app.use(RequestParser.bodyParser())
ctx.response.body = ctx['body']
/* {
  'text': xxx
}*/

完整示例

import { Application, Router, Next, type BodyType, type BodyOptions } from "https://deno.land/x/oak@v12.5.0/mod.ts";
import RequestParser from 'https://deno.land/x/m_oak_request_parser/mod.js'
// import { getParser, bodyParser } from 'https://deno.land/x/m_oak_request_parser/mod.js'

const app = new Application();
const router = new Router();

app.use(RequestParser.bodyParser())

router.post("/upload", (ctx: any) => {
  ctx.response.body = ctx['body']
});

app.use(router.routes());
app.use(router.allowedMethods());

console.log('服务运行于: http://localhost:9000');
await app.listen({ port: 9000 });

deno.land

deno.land/x/m_oak_req…

oak request-parser

github.com/m-deno/m-oa…