Node.js http 模块
http 模块是 Node.js 创建 HTTP 服务器和客户端的核心模块。
应用场景
- 创建 Web 服务器
- 构建 RESTful API
- 代理服务器(负载均衡、缓存、跨域)
- 静态文件服务器
创建服务器
js
const http = require('node:http')
const url = require('node:url')
http.createServer((req, res) => {
const { pathname, query } = url.parse(req.url, true)
if (req.method === 'POST') {
if (pathname === '/post') {
let data = ''
req.on('data', (chunk) => data += chunk) // 接收 POST 数据
req.on('end', () => {
res.setHeader('Content-Type', 'application/json')
res.statusCode = 200
res.end(data) // 原样返回
})
} else {
res.statusCode = 404
res.end('Not Found')
}
} else if (req.method === 'GET') {
if (pathname === '/get') {
console.log(query.a) // 读取查询参数 ?a=xxx
res.end('get success')
}
}
}).listen(98, () => console.log('server running on port 98'))关键点
| 属性/方法 | 说明 |
|---|---|
req.method | 请求方法:'GET' / 'POST' / 'PUT' / 'DELETE' |
req.url | 请求路径(含查询字符串) |
url.parse(req.url, true) | 解析 URL,pathname 路径 + query 查询参数对象 |
req.on('data', cb) | 接收 POST 请求体(分块) |
req.on('end', cb) | 请求体接收完毕 |
res.setHeader(k, v) | 设置响应头 |
res.statusCode | 设置 HTTP 状态码 |
res.end(data) | 发送响应并结束 |
调试(.http 文件)
VSCode 安装 REST Client 插件后,可直接写 .http 文件调试:
POST http://localhost:98/post HTTP/1.1
Content-Type: application/json
{"name":"小满zs"}
### 分隔请求
GET http://localhost:98/get?a=1&b=2 HTTP/1.1