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/`);
});
相关推荐
正经教主2 天前
【Trae+AI】和Trae学习搭建App_03:后端API开发原理与实践(已了解相关知识的可跳过)
后端·express
想睡好2 天前
express中间件(java拦截器)
java·中间件·express
正经教主2 天前
【Trae+AI】Express框架01:教程示例搭建及基础原理
前端框架·express
gongzemin3 天前
使用阿里云ECS部署Express
后端·node.js·express
Json____7 天前
使用node Express 框架框架开发一个前后端分离的二手交易平台项目。
java·前端·express
Moshow郑锴10 天前
CSP 配置指南:SpringBoot/Express 实操 + 多域名适配,防 XSS 攻击超简单
spring boot·express·xss
tryCbest10 天前
Node.js使用Express+SQLite实现登录认证
sqlite·node.js·express
tryCbest17 天前
Node.js使用Express框架解决中文乱码问题
node.js·express
谢尔登25 天前
【Nest】基本概念
javascript·node.js·express
风继续吹..1 个月前
Express.js 入门指南:从零开始构建 Web 应用
前端·javascript·express