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

准备工作

安装依赖

bash 复制代码
npm init -y
npm i koa

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

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

js 复制代码
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 否则没有等待效果

js 复制代码
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

javascript 复制代码
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

bash 复制代码
nodemon server.js

输入账号密码,点击提交

koa-bodyparser

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

bash 复制代码
npm i koa-bodyparser

用法:

js 复制代码
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;
});

业务里添加逻辑

javascript 复制代码
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

javascript 复制代码
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(); // 完成后需要继续向下执行
    };
};

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

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

启动服务,效果一样:

相关推荐
眠りたいです2 天前
基于脚手架微服务的视频点播系统-脚手架开发部分-brpc中间件介绍与使用及二次封装
c++·微服务·中间件·rpc·架构·brpc
眠りたいです2 天前
基于脚手架微服务的视频点播系统-脚手架开发部分-jsoncpp,protobuf,Cpp-httplib与WebSocketpp中间件介绍与使用
c++·websocket·微服务·中间件·json·protobuf·cpp-httplib
深蓝电商API3 天前
Scrapy 中间件详解:自定义下载器与爬虫的 “拦截器”
爬虫·scrapy·中间件
知行合一。。。4 天前
SOFA 架构--02--核心中间件与工具
中间件·架构
谢尔登4 天前
【Nest】日志记录
javascript·中间件·node.js
SirLancelot15 天前
MinIO-基本介绍(一)基本概念、特点、适用场景
后端·云原生·中间件·容器·aws·对象存储·minio
RunningShare6 天前
云原生时代的数据流高速公路:深入解剖Apache Pulsar的架构设计哲学
大数据·中间件·apache·pulsar
野熊佩骑7 天前
一文读懂Redis之数据持久化
linux·运维·数据库·redis·缓存·中间件·centos
武子康7 天前
AI-调查研究-90-具身智能 机器人数据采集与通信中间件全面解析:ROS/ROS2、LCM 与工业总线对比
人工智能·ai·中间件·机器人·职场发展·个人开发·具身智能
十五年专注C++开发7 天前
通信中间件 Fast DDS(三) :fastddsgen的安装与使用
linux·c++·windows·中间件·跨平台