88 # express 应用和路由的分离

简介: 88 # express 应用和路由的分离

上一节实现了应用和创建应用的分离,这一节来实现应用和路由的分离

application.js

const http = require("http");
const Router = require("./router");
function Application() {
    this._router = new Router();
}
Application.prototype.get = function (path, handler) {
    this._router.get(path, handler);
};
Application.prototype.listen = function () {
    const server = http.createServer((req, res) => {
        function next() {
            res.end(`kaimo-express Cannot ${req.method} ${req.url}`);
        }
        this._router.handle(req, res, next);
    });
    server.listen(...arguments);
};
module.exports = Application;

然后我们新建 router 文件夹,里面添加 index.js,添加代码

const url = require("url");
function Router() {
    // 维护所有的路由
    this.stack = [];
}
Router.prototype.get = function (path, handler) {
    this.stack.push({
        path,
        method: "get",
        handler
    });
};
Router.prototype.handle = function (req, res, next) {
    const { pathname } = url.parse(req.url);
    const requestMethod = req.method.toLowerCase();
    for (let i = 0; i < this.stack.length; i++) {
        let { path, method, handler } = this.stack[i];
        if (path === pathname && method === requestMethod) {
            return handler(req, res);
        }
    }
    // 处理不了的直接走 next
    next();
};
module.exports = Router;

启动测试代码:

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/`);
});

目录
相关文章
|
6月前
|
中间件
95 # express 二级路由的实现
95 # express 二级路由的实现
32 0
|
6月前
87 # express 应用和创建应用的分离
87 # express 应用和创建应用的分离
12 0
|
7月前
|
JSON JavaScript 中间件
node.js中Express框架路由,中间件
node.js中Express框架路由,中间件
|
3月前
|
Web App开发 JSON 中间件
express学习 - (3)express 路由
express学习 - (3)express 路由
74 1
|
3月前
|
JavaScript 前端开发 中间件
Node.js—Express使用、Express 路由 、Express 中间件、托管静态资源、使用 Express 写接口、node.js链接sqlite数据库
Node.js—Express使用、Express 路由 、Express 中间件、托管静态资源、使用 Express 写接口、node.js链接sqlite数据库
114 0
|
4月前
|
测试技术
【Express】—路由配置
【Express】—路由配置
|
4月前
【Express】—Express路由请求
【Express】—Express路由请求
|
4月前
Express简单路由使用
Express简单路由使用
|
6月前
|
中间件
94 # express 兼容老的路由写法
94 # express 兼容老的路由写法
22 0
|
6月前
|
弹性计算 开发框架 JavaScript
SAP UI5 应用开发教程之五十五 - 如何将本地 SAP UI5 应用通过 Node.js Express 部署到公网上试读版
SAP UI5 应用开发教程之五十五 - 如何将本地 SAP UI5 应用通过 Node.js Express 部署到公网上试读版
69 0