Express 原理-总述

2023-12-08
Express
1296

Express 是一种保持最低程度规模的灵活 Node.js Web 应用程序框架,为 Web 和移动应用程序提供一组强大的功能。 它扩展 node http 模块,扩展常用的 web 能力,提供更加友好的 api,让web server开发更加便捷

Node http

先来看一个基础的 node http 服务写法

const http = require('http');

// Create a local server to receive data from
const server = http.createServer((req, res) => {
  if (request.method === 'GET' && request.url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.write('nihao');
    res.end();
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.write('Not Found');
    res.end();
  }
});

server.listen(8000);
  1. http.createServer 创建一个web服务
  2. server.listen 设置监听接口,启动服务
  3. request.method、request.url 获取请求的参数
  4. response.writeHead、response.write 设置返回数据
  5. response.end 发送请求

基于上面的代码,我们可以简单分析出几个问题点

  1. method + url 确定一个路由方式繁琐
  2. 所有请求处理逻辑都在一个函数中,欠缺模块化能力
  3. 返回数据需要手动设置 content-type status,然后再传输数据

针对以上的一些问题,express 框架提供了相对应的解决方案,将刀耕火种的原始时期,进化到模块化的青铜时期

Express 与 node http 结合

Express 的内核是一个 http 服务的处理器,起 web 服务还得需要 node http,他们结合的方式如下:

Express

function createApplication() {
  var app = function(req, res, next) {
    app.handle(req, res, next);
  };
  // ...

  return app
}

exports = module.exports = createApplication;

业务代码

const http = require('http');
const app = createApplication()

const server = http.createServer(app)

server.listen(8000);

可以发现 express 是实现的一个 req, res 和 handle 能力,来处理 http 请求

之后我们来看 express 具体是怎么扩展 Http 的能力

扫码体验小程序版