83 # The use and implementation of static service middleware koa-static

Static service middleware: koa-static

The middleware can decide whether to execute downwards. If it can handle it, it will directly complete the processing. If it cannot handle it, the next method will continue to execute downwards.

Create a new public folder and add index.html、style.cssfiles in it

<!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>
body {
    
    
    background-color: pink;
}

koa-static

npm i koa koa-static

usage:

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.jsUsed in business codekoa-static

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);

Start the service and accesshttp://localhost:3000/index.html

Insert image description here

nodemon static.js

To implement your own below koa-static, you need to install mime

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();
        }
    };
};

Insert image description here

Insert image description here

Guess you like

Origin blog.csdn.net/kaimo313/article/details/132816357