Deno 几种常用的传参方式

视频讲解:

https://www.bilibili.com/video/BV1BT4y1E7Nh/?p=8

我们一起来完成以下步骤:

  1. 以key-value方式传参

  2. 以value方式传参

  3. 使用oak Helpers 接受传参

  4. body 传参

  5. header 传参

#controllers/controller.ts


import { getQuery } from "https://deno.land/x/oak/helpers.ts";
const { cwd } = Deno;

class Controller {
    static async hello(ctx: any){
        //cwd获取当前工程目录 
        //注意 ' !== `
        ctx.render(`${cwd()}/views/index.ejs`,{
            title:"Testing",
            data:{name:" Deepincoding"}
        }); 
    }

    //key-value 方式传参
    static async searchParams(ctx: any){
        var id = ctx.request.url.searchParams.get("id");
        var name = ctx.request.url.searchParams.get("name");
        ctx.response.body= {id:`${id}`,name:`${name}`}
    }

    //value 方式传参
    static async params(ctx: any){
        var id = ctx.params.id;
        var name = ctx.params.name;
        ctx.response.body= {id:`${id}`,name:`${name}`}
    }

    //oak Helpers 接受参数
    static async helper(ctx: any){
        var paramsValue =  getQuery(ctx, { mergeParams: true });
        ctx.response.body= paramsValue;
    }

    //body 传参
    static async body(ctx: any){
        var bodyValue = await ctx.request.body();
        ctx.response.body= bodyValue.value;
    }

    //header 传参
    static async header(ctx: any){
        var id = ctx.request.headers.get("id");
        var name =  ctx.request.headers.get("name");
        ctx.response.body= {id:`${id}`,name:`${name}`}
    }

}

export default Controller;

#routers/index.ts

import { Router } from "https://deno.land/x/oak/mod.ts";
import Controller from "../controllers/Controller.ts";

const router = new Router();

router.get("/",Controller.hello);

router.get("/searchParams",Controller.searchParams);
router.get("/params/:id/:name",Controller.params);

router.get("/helper/:id/:name",Controller.helper);
router.get("/helper",Controller.helper);

router.post("/body",Controller.body);
router.post("/header",Controller.header);


export default router;

#main.ts



import { Application } from "https://deno.land/x/oak/mod.ts"
import {viewEngine,engineFactory,adapterFactory} from "https://deno.land/x/view_engine/mod.ts";
import router from "./routers/index.ts";

const ejsEngine = engineFactory.getEjsEngine();
const oakAdapter = adapterFactory.getOakAdapter();

const app = new Application();
app.use(viewEngine(oakAdapter,ejsEngine));
app.use(router.routes());
app.use(router.allowedMethods());

await app.listen({port: 8000 })


 

你可能感兴趣的:(Deno,传参,Deno)