express 源码实现(一)

本文详细解读了Express框架的创建过程,涉及应用层的创建、`Application`和`Router`模块的实现,以及如何通过路由处理HTTP请求。重点介绍了核心构造函数和关键API的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

express 源码实现(一)

1.首先说一下大概使用方式

const express = require('express'); 

const app = express(); // 执行函数返回一个app 应用
// 发起get 请求
app.get('/', function(req, res) {
	// 结束 返回内容
    res.end('home')
})
app.get('/about', function(req, res) {
    res.end('about')
})
// 监听 3000 端口
app.listen(3000,function () {
	// 成功后的回调函数
    console.log(`server start 3000`)
});

2.express 主要分三大部分
①创建应用层(包应用层)
②应用层(包路由层)
③路由层
2.1 实现组织建构
①创建应用层js文件

express.js 入口文件 创建createApplication构造函数,也就是创建应用层

const  Application = require('./application')
	function createApplication (){

	    const app = new Application();// 这个是应用层
	    return app
	}

创建应用层application.js 文件;
首要任务:
1.创建http 服务

	const http = require('http');
	const Router = require('./router');
	function Application(){
		// 这里创建一个router 实例,因为我只是创建应用层,路由的事件不归我管,交给专人处理
		this._router = new Router()
	}
	// 创建服务
	Application.protoType.listen = function(...args){// 接受参数,端口号,以及回调函数
		const server = http.createServer((req, res)=>{
		//请求到来时的回调函数,里面有请求方法,请求路径等等
		// 既然有请求方法请求路径,那我们可以根据这两个条件判断执行用户具体哪个回调函数
		  // 有可能路由系统无法处理,就让应用自己来处理
        function done() {
            res.end(`Cannot ${req.method} ${req.url}`)
        }
        // 交给路由来匹配规则
        this._router.handle(req, res, done)
		})
		server.listen(...args);
	}
	// 创建请求
	Application.protoType.get= function(path,handler){
		this._router.get(path,handler)
	}
	module.exports = Application;

2.创建router 函数,处理请求
router.js

	const url = require('url');
	function Router(){
		// 存储	Application 发过来 请求以及回调函数
		this.stack = [];
	}
	Router.protoType.get = function(path,handler){
		this.stack.push({path,handler,method:'get'})
	}
	Router.protoType.handle= function(path,handler){
		let { pathname } = url.parse(req.url);
    	let requestMethod = req.method.toLowerCase();
	    for (let i = 0; i < this.stack.length; i++) {
	        let { path, method, handler } = this.stack[i]
	        if ((pathname == path) && method === requestMethod) {
	            return handler(req, res);
	        }
	    }
	    	done();
	}

module.exports = Router;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值