上一节实现了应用和创建应用的分离,这一节来实现应用和路由的分离
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/`); });