• 87 # express 应用和创建应用的分离


    1. 创建应用的过程和应用本身要进行分离。
    2. 路由和创建应用的过程也做一个分离。

    下面实现创建应用的过程和应用本身要进行分离:

    express.js

    const Application = require("./application");
    
    function createApplication() {
        // 通过类来实现分离操作
        return new Application();
    }
    
    module.exports = createApplication;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    每次创建一个应用,路由系统应该是毫无关系的,应该创建一个全新的路由系统

    新建 application.js

    const http = require("http");
    const url = require("url");
    
    function Application() {
        this.routers = [
            {
                path: "*",
                method: "all",
                handler: (req, res) => {
                    res.end(`kaimo-express Cannot ${req.method} ${req.url}`);
                }
            } // 默认路由
        ];
    }
    
    Application.prototype.get = function (path, handler) {
        this.routers.push({
            path,
            method: "get",
            handler
        });
    };
    
    Application.prototype.listen = function () {
        const server = http.createServer((req, res) => {
            const { pathname } = url.parse(req.url);
            const requestMethod = req.method.toLowerCase();
            for (let i = 1; i < this.routers.length; i++) {
                let { path, method, handler } = this.routers[i];
                if (path === pathname && method === requestMethod) {
                    return handler(req, res);
                }
            }
            return this.routers[0].handler(req, res);
        });
        server.listen(...arguments);
    };
    
    module.exports = Application;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39

    测试一下:

    const express = require("./kaimo-express");
    const app = express();
    
    // 调用回调时 会将原生的 req 和 res 传入(req,res 在内部也被扩展了)
    // 内部不会将回调函数包装成 promise
    app.get("/", (req, res) => {
        res.end("ok");
    });
    
    app.get("/add", (req, res) => {
        res.end("add");
    });
    
    app.listen(3000, () => {
        console.log(`server start 3000`);
        console.log(`在线访问地址:http://localhost:3000/`);
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    在这里插入图片描述

  • 相关阅读:
    【计算机网络】网络层(五)—— IPv6总结
    Mongodb 删除集合数据后如何释放磁盘空间
    全真模拟题!PMP提分必练
    【PS-8】选区
    Go语言中入门Hello World以及IDE介绍
    日期时间格式化 @JsonFormat与@DateTimeFormat
    【剑指 Offer】矩阵中的路径
    WISE 2019 | ML-GCN:多标签图节点分类的半监督图嵌入
    语雀停服8小时,P0级事故,故障原因和补偿来了。
    PHP登录strcmp函数绕过
  • 原文地址:https://blog.csdn.net/kaimo313/article/details/132958010