- 最简单的封装: ```javascript
将请求封装为[[‘get’,’/xxx’],{请求头},’请求体’]
将响应封装为[status,{响应头},’响应体’]
[status,{响应头},’响应体’]是最基础的东西,只需要这三个东西,就可以展示一个页面了。
- Node.js的封装```javascript- 封装在http模块中了- 使用request读取请求可以在request这个对象里面找到[['get','/xxx'],{请求头},'请求体']这些东西属于IncomingMessage这个类- 使用response设置响应可以在response这个对象里面找到[status,{响应头},'响应体']属于ServerResponse这个类
- Express的封装
Express在nodej的基础上,再封装了一层
所以它的封装级别高一点点,只需要理解Express的编程模型即可。
中文文档:https://www.expressjs.com.cn/
express-demo-1
创建项目并上传到git。
- yarn init
- git init
- git add .
- git commit -m init
- 到github上创建一个仓库

- 复制粘贴
初始化项目
- yarn add express
- 然后直接抄官方文档的helloworld
- https://www.expressjs.com.cn/starter/hello-world.html
app.js:
const express = require('express')const app = express()const port = 3000app.get('/', (req, res) => res.send('Hello World!'))app.listen(port, () => console.log(`Example app listening on port ${port}!`))
抄完之后运行
- node app.js
- 打开http://localhost:3000/ 就可以看到helloworld了
- 或者 $ curl http://localhost:3000/
- node app.js
抄完之后改
全局安装node-dev 改了之后会自动刷新。npm install -g node-dev
改一下:
const express = require('express')const app = express()const port = 4000app.get('/xxx', (req, res) => res.send('你好1!'))app.listen(port, () => console.log(`Example app listening on port ${port}!`))
改了端口为4000,get的路径为/xxx
通过这次的CRM学习,很快就搞清楚了:
- app = express()
- 这个app应该是核心
- app.get(‘/xxx’,fn) 用于对GET/xxx请求作出响应
- app.listen(3000,fn) 用于开启端口监听
用ts再做一遍

如果tsc —init 报错:tsc不是命令
npm install -g concurrently
npm install -g lite-server
npm install -g typescript
tsc —init
就可以了
import express from 'express';const app = express();app.get('/', function (request, response) {response.send('你好');});const port = 4000;app.listen(port, function () {console.log(`Example app listening on port ${port}`);});
