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();
        }
    };
};
相关推荐
白总Server19 分钟前
多智能体系统的中间件架构
linux·运维·服务器·中间件·ribbon·架构·github
晓华-warm10 小时前
国产免费工作流引擎star 5.9k,Warm-Flow版本升级1.7.0(新增大量好用功能)
java·中间件·流程图·开源软件·flowable·工作流·activities
李宥小哥13 小时前
Redis01-基础-入门
缓存·中间件
lee_yanyi14 小时前
《一键式江湖:Docker Compose中间件部署108式》开篇:告别“配置地狱”,从此笑傲云原生武林!》
docker·云原生·中间件
李宥小哥17 小时前
Redis03-基础-C#客户端
开发语言·缓存·中间件·c#
佳腾_1 天前
【Web应用服务器_Tomcat】二、Tomcat 核心配置与集群搭建
java·前端·中间件·tomcat·web应用服务器
暮乘白帝过重山1 天前
路由逻辑由 Exchange 和 Binding(绑定) 决定” 的含义
开发语言·后端·中间件·路由流程
w23617346011 天前
Apache中间件解析漏洞与安全加固
安全·中间件·apache
Harbor Lau2 天前
Linux常用中间件命令大全
linux·运维·中间件
佳腾_3 天前
【Web应用服务器_Tomcat】一、Tomcat基础与核心功能详解
java·前端·中间件·tomcat·web应用服务器