express本地监听端口运行原理初探

2,586 阅读1分钟

初学express的时候都会看到这么一段代码:

var express = require('express');
var app = express();
app.get('/', function (req, res) { // get方法表示处理客户端发出的GET请求,参数分别是访问路径和回调函数(req参数-客户端发来的HTTP请求,res-发向客户端的HTTP响应),
  res.send('Hello World');
});
app.listen(3000, function () {
  console.log('app is listening at port 3000');
});

node代码监听了3000端口,为什么通过访问http://localhost:3000/ 可以看见hello world?
首先express框架建立在node.js内置的http模块(http 模块主要用于搭建 HTTP 服务端 和 客户端)上,express框架的核心是对http模块的再包装
http模块生成服务器的原始代码如下:

var http = require("http");
var app = http.createServer(function(request, response) { // http模块的createServer方法接受一个回调函数,参数分别为request对象(http请求)和response对象(http回应)
  response.writeHead(200, {"Content-Type": "text/plain"}); // 响应为html文本
  response.end("Hello world!");
});
app.listen(3000, "localhost"); // 启动服务器

所以可以这么理解:app.get('/', function (req, res) { });就是上面代码的另一种包装