当前位置: 首页 > news >正文

82 # koa-bodyparser 中间件的使用以及实现

准备工作

安装依赖

npm init -y
npm i koa

在这里插入图片描述

koa 文档:https://koajs.cn/#

koa 中不能用回调的方式来实现,因为 async 函数执行的时候不会等待回调完成

app.use(async (ctx, next) => {
    console.log(ctx.path, ctx.method);
    if (ctx.path == "/login" && ctx.method === "POST") {
        const arr = [];
        ctx.req.on("data", function (chunk) {
            arr.push(chunk);
        });
        ctx.req.on("end", function () {
            const result = Buffer.concat(arr).toString();
            console.log("result---->", result);
            ctx.body = result;
        });
    } else {
        next();
    }
});

koa 中所有的异步都必须是 promise,只有 promise 才有等待效果,必须所有的 next 方法前需要有 await、return 否则没有等待效果

app.use(async (ctx, next) => {
    console.log(ctx.path, ctx.method);
    if (ctx.path == "/login" && ctx.method === "POST") {
        await new Promise((resolve, reject) => {
            const arr = [];
            ctx.req.on("data", function (chunk) {
                arr.push(chunk);
            });
            ctx.req.on("end", function () {
                const result = Buffer.concat(arr).toString();
                console.log("result---->", result);
                ctx.body = result;
                resolve();
            });
        });
    } else {
        await next();
    }
});

实现一个表单提交功能 server.js

const Koa = require("koa");

const app = new Koa();

app.use((ctx, next) => {
    // 路径是 /login get 方式
    // ctx 包含了 request response req res
    console.log(ctx.path, ctx.method);
    if (ctx.path == "/login" && ctx.method === "GET") {
        ctx.body = `
            <form action="/login" method="post">
                用户名:<input type="text" name="username"/><br/>
                密码:<input type="password" name="password"/><br/>
                <button>提交</button>
            </form>
        `;
    } else {
        return next();
    }
});

app.use(async (ctx, next) => {
    console.log(ctx.path, ctx.method);
    if (ctx.path == "/login" && ctx.method === "POST") {
        await new Promise((resolve, reject) => {
            const arr = [];
            ctx.req.on("data", function (chunk) {
                arr.push(chunk);
            });
            ctx.req.on("end", function () {
                const result = Buffer.concat(arr).toString();
                console.log("result---->", result);
                ctx.body = result;
                resolve();
            });
        });
    } else {
        await next();
    }
});

app.on("error", function (err) {
    console.log("error----->", err);
});

app.listen(3000);

启动服务,访问 http://localhost:3000/login

nodemon server.js

在这里插入图片描述

输入账号密码,点击提交

在这里插入图片描述

koa-bodyparser

下面使用 koa-bodyparser 简化逻辑,安装 koa-bodyparser,https://www.npmjs.com/package/koa-bodyparser

npm i koa-bodyparser

用法:

const Koa = require('koa');
const bodyParser = require('koa-bodyparser');

const app = new Koa();
app.use(bodyParser());

app.use(async ctx => {
  // the parsed body will store in ctx.request.body
  // if nothing was parsed, body will be an empty object {}
  ctx.body = ctx.request.body;
});

业务里添加逻辑

const Koa = require("koa");
const bodyParser = require("koa-bodyparser");
const app = new Koa();
app.use(bodyParser());

app.use((ctx, next) => {
    // 路径是 /login get 方式
    // ctx 包含了 request response req res
    console.log(ctx.path, ctx.method);
    if (ctx.path == "/login" && ctx.method === "GET") {
        ctx.body = `
            <form action="/login" method="post">
                用户名:<input type="text" name="username"/><br/>
                密码:<input type="password" name="password"/><br/>
                <button>提交</button>
            </form>
        `;
    } else {
        return next();
    }
});

app.use(async (ctx, next) => {
    console.log(ctx.path, ctx.method);
    if (ctx.path == "/login" && ctx.method === "POST") {
        ctx.body = ctx.request.body;
    } else {
        await next();
    }
});

app.on("error", function (err) {
    console.log("error----->", err);
});

app.listen(3000);

效果也是一样的

下面自己实现 koa-bodyparser

const querystring = require("querystring");
console.log("使用的是 kaimo-koa-bodyparser 中间件");
// 中间件的功能可以扩展属性、方法
module.exports = function () {
    return async (ctx, next) => {
        await new Promise((resolve, reject) => {
            const arr = [];
            ctx.req.on("data", function (chunk) {
                arr.push(chunk);
            });
            ctx.req.on("end", function () {
                if (ctx.get("content-type") === "application/x-www-form-urlencoded") {
                    const result = Buffer.concat(arr).toString();
                    console.log("kaimo-koa-bodyparser-result---->", result);
                    ctx.request.body = querystring.parse(result);
                }
                resolve();
            });
        });
        await next(); // 完成后需要继续向下执行
    };
};

将业务代码的引用自己实现的

// 使用自己实现的 koa-bodyparser
const bodyParser = require("./kaimo-koa-bodyparser");

启动服务,效果一样:

在这里插入图片描述

相关文章:

  • Java程序连接 Mysql 超时问题 - 数据包过大,导致超时,# 配置网络超时时间 socketTimeout: 1800000
  • Python3.10 IDLE更换主题
  • 对于每种情况分别统计概率来计算期望+树上连通块统计:ARC165E
  • Prometheus 监控指南:如何可靠地记录数字时间序列数据
  • Java-API简析_java.net.Inet6Address类(基于 Latest JDK)(浅析源码)
  • 华为认证 | HCIA、HCIP、HCIE,难度区别在哪里?
  • 请问一下就是业务概念模型和业务逻辑模型有啥关系
  • 【Linux】网络篇:UDP、TCP 网络接口及使用
  • 分布式调度 Elastic-job
  • numpy详解
  • Prompt 策略:代码库 AI 助手的语义化搜索设计
  • 写一篇nginx配置指南
  • Oracle的 dblink 学习笔记
  • 使用stelnet进行安全的远程管理
  • 机器学习 day35(决策树)
  • Linux的调试工具 - gdb(超详细)
  • 〖Python网络爬虫实战㉟〗- 极验验证码的识别
  • 【VsCode】SSH远程连接Linux服务器开发,搭配cpolar内网穿透实现公网访问(1)
  • LeNet-5
  • vue3父子组件传对象,子组件访问修改父组件对象中的属性值
  • 上影新片《密档》杀青,全新角度演绎石库门秘战
  • 张广智当选陕西省慈善联合会会长
  • 全国人大常委会调研组在宁波调研,张庆伟带队钟山易炼红参加
  • 依托空域优势,浦江镇将建设上海首个“低空融合飞行示范区”
  • 图忆|温州旅沪先贤的家国情怀
  • 九江市人大常委会原党组成员、副主任戴晓慧主动交代问题,正接受审查调查