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

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

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

express.js

javascript 复制代码
const Application = require("./application");

function createApplication() {
    // 通过类来实现分离操作
    return new Application();
}

module.exports = createApplication;

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

新建 application.js

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

测试一下:

javascript 复制代码
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/`);
});
相关推荐
GDAL3 天前
express.urlencoded深入全面讲解教程
express·urlencoded
GDAL4 天前
express.urlencoded和fetch结合使用
express·form·fetch
GDAL4 天前
express.json 深入全面讲解教程
json·express
GDAL4 天前
Express 中 CORS 跨域问题解决教程
express·cors
GDAL4 天前
express.text和fetch配合使用深入全面教程
express·text
GDAL5 天前
Express POST 请求深入全面讲解教程
express
正经教主6 天前
【Trae+AI】和Trae学习搭建App_2.1:第3章·手搓后端基础框架Express
人工智能·后端·学习·express
你真的可爱呀9 天前
2.Express 核心语法与路由
中间件·node.js·express
骚团长9 天前
SQL server 配置管理器-SQL server 服务-远程过程调试失败 [0x800706be]-(Express LocalDB卸载掉)完美解决!
java·服务器·express
你真的可爱呀9 天前
1.基础环境搭建与核心认知
node.js·express