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/`);
});
相关推荐
Json____3 天前
使用node-Express框架写一个学校宿舍管理系统练习项目-前后端分离
node·express·前后端分离·宿舍管理
草木红5 天前
express 框架基础和 EJS 模板
arcgis·node.js·express
HWL567912 天前
在本地使用Node.js和Express框架来连接和操作远程数据库
node.js·express
SEO-狼术12 天前
Add-in Express for Microsoft Office
microsoft·express
盛夏绽放21 天前
Node.js 和 Express 面试问题总结
面试·职场和发展·node.js·express
天天进步20151 个月前
Node.js中Express框架入门教程
node.js·express
mosen8681 个月前
易混淆的CommonJS和ESM(ES Module)及它们区别
javascript·node.js·express
一枚小小程序员哈1 个月前
基于Vue + Node能源采购系统的设计与实现/基于express的能源管理系统#node.js
vue.js·node.js·express
一枚小小程序员哈1 个月前
基于Vue的个人博客网站的设计与实现/基于node.js的博客系统的设计与实现#express框架、vscode
vue.js·node.js·express
茶茶只知道学习1 个月前
Express中间件和路由及响应方法
中间件·express