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/`);
});
相关推荐
天天进步20154 天前
Node.js中Express框架入门教程
node.js·express
mosen8684 天前
易混淆的CommonJS和ESM(ES Module)及它们区别
javascript·node.js·express
一枚小小程序员哈9 天前
基于Vue + Node能源采购系统的设计与实现/基于express的能源管理系统#node.js
vue.js·node.js·express
一枚小小程序员哈9 天前
基于Vue的个人博客网站的设计与实现/基于node.js的博客系统的设计与实现#express框架、vscode
vue.js·node.js·express
茶茶只知道学习16 天前
Express中间件和路由及响应方法
中间件·express
计算机毕设定制辅导-无忧学长20 天前
InfluxDB 与 Node.js 框架:Express 集成方案(二)
node.js·express
啃火龙果的兔子22 天前
Node.js (Express) + MySQL + Redis构建项目流程
mysql·node.js·express
计算机毕设定制辅导-无忧学长24 天前
InfluxDB 与 Node.js 框架:Express 集成方案(一)
node.js·express
gongzemin1 个月前
使用Node.js开发微信第三方平台后台
微信小程序·node.js·express
都给我1 个月前
服务器中涉及节流(Throttle)的硬件组件及其应用注意事项
服务器·网络·express