83 # 静态服务中间件 koa-static 的使用以及实现

静态服务中间件:koa-static

中间件可以决定是否向下执行,如果自己可以处理,那么直接处理完毕结束,如果自己处理不了,next 方法会继续向下执行

新建 public 文件夹,里面添加 index.html、style.css 文件

html 复制代码
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>凯小默测试静态服务中间件koa-static</title>
        <link rel="stylesheet" href="./style.css" />
    </head>

    <body>
        <h1>凯小默测试静态服务中间件koa-static</h1>
    </body>
</html>
css 复制代码
body {
    background-color: pink;
}

koa-static

bash 复制代码
npm i koa koa-static

用法:

js 复制代码
const serve = require('koa-static');
const Koa = require('koa');
const app = new Koa();
 
// $ GET /package.json
app.use(serve('.'));
 
// $ GET /hello.txt
app.use(serve('test/fixtures'));
 
// or use absolute paths
app.use(serve(__dirname + '/test/fixtures'));
 
app.listen(3000);
 
console.log('listening on port 3000');

业务代码 static.js 中使用 koa-static

javascript 复制代码
const Koa = require("koa");
const path = require("path");
const bodyParser = require("koa-bodyparser");
// 使用自己实现的中间件
// const static = require("koa-static");
const static = require("./kaimo-koa-static");
const app = new Koa();
app.use(bodyParser());
app.use(static(__dirname));
app.use(static(path.resolve(__dirname, "public")));

app.use((ctx, next) => {
    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);

启动服务,访问 http://localhost:3000/index.html

bash 复制代码
nodemon static.js

下面实现自己的 koa-static,需要安装 mime

javascript 复制代码
const path = require("path");
const fs = require("fs").promises;
const mime = require("mime");

console.log("使用的是 kaimo-koa-static 中间件");
module.exports = function static(root) {
    return async (ctx, next) => {
        let filePath = path.join(root, ctx.path);
        try {
            let statObj = await fs.stat(filePath);
            // 判断是否是文件
            if (statObj.isFile()) {
                ctx.type = mime.getType(filePath) + ";charset=utf-8";
                ctx.body = await fs.readFile(filePath);
            } else {
                await next();
            }
        } catch (e) {
            await next();
        }
    };
};
相关推荐
纪莫20 小时前
Kafka如何保证「消息不丢失」,「顺序传输」,「不重复消费」,以及为什么会发生重平衡(reblanace)
java·分布式·后端·中间件·kafka·队列
要开心吖ZSH21 小时前
java八股文-中间件-参考回答
微服务·中间件·消息中间件
db_murphy2 天前
知识篇 | 中间件会话保持和会话共享有啥区别?
中间件
拷贝码农卡卡东2 天前
宿主机与容器通过 rmw_cyclonedds_cpp中间件进行ros2结点之间的通讯的相关注意事项
中间件
墨鸦_Cormorant4 天前
MQTT(轻量级消息中间件)基本使用指南
mqtt·中间件·消息中间件
Python私教6 天前
从“Hello World”到“高并发中间件”:Go 语言 2025 系统学习路线图
学习·中间件·golang
UrSpecial6 天前
进程间通信:消息队列
中间件
EndingCoder9 天前
Next.js 中间件:自定义请求处理
开发语言·前端·javascript·react.js·中间件·全栈·next.js
十五年专注C++开发9 天前
通信中间件 Fast DDS(一) :编译、安装和测试
linux·c++·windows·中间件·cmake·vcpkg
在未来等你11 天前
RabbitMQ面试精讲 Day 17:消费者调优与并发消费
中间件·面试·消息队列·rabbitmq