Node.js HTTP模块详解:从入门到实战开发
一、HTTP模块概述
HTTP模块是Node.js的核心模块,用于创建HTTP服务器和客户端,处理网络请求和响应。作为构建Web服务的基础,它提供了底层的API支持。
1.1 模块特点
- 事件驱动:基于事件机制处理请求
- 流式处理:支持请求/响应数据流
- 轻量高效:不依赖第三方库
- 灵活可控:提供底层控制能力
二、创建HTTP服务器
2.1 基本服务器
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello CSDN!\n');
});
server.listen(28081, () => {
console.log('Server running at http://localhost:3000/');
});
2.2 核心对象解析
对象 | 作用 |
---|---|
http.Server | HTTP服务器实例 |
http.IncomingMessage | 请求对象(req) |
http.ServerResponse | 响应对象(res) |
三、请求与响应处理
3.1 请求解析
// 获取请求信息
server.on('request', (req, res) => {
console.log(`Method: ${req.method}`);
console.log(`URL: ${req.url}`);
console.log(`Headers: ${JSON.stringify(req.headers)}`);
// 获取请求体
let body = [];
req.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
body = Buffer.concat(body).toString();
console.log('Body:', body);
});
});
3.2 响应控制
// 设置响应
res.statusCode = 200; // 状态码
res.setHeader('Content-Type', 'application/json'); // 响应头
// 分块发送响应
res.write('First part\n');
res.write('Second part\n');
res.end('Final part\n');
// 重定向
res.writeHead(302, {
'Location': '/new-path'
});
res.end();
四、实战应用场景
4.1 RESTful API实现
const server = http.createServer((req, res) => {
const { method, url } = req;
if(method === 'GET' && url === '/api/users') {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify([{id: 1, name: '张三'}]));
}
else if(method === 'POST' && url === '/api/users') {
// 处理POST请求...
}
else {
res.writeHead(404);
res.end('Not Found');
}
});
4.2 静态文件服务器
const fs = require('fs');
const path = require('path');
http.createServer((req, res) => {
let filePath = path.join(__dirname, 'public', req.url);
fs.readFile(filePath, (err, content) => {
if(err) {
if(err.code === 'ENOENT') {
res.writeHead(404);
res.end('File not found');
} else {
res.writeHead(500);
res.end('Server error');
}
} else {
res.writeHead(200);
res.end(content);
}
});
}).listen(28081);
五、性能优化与安全
5.1 最佳实践
- 连接复用:启用keep-alive
- 请求限流:防止DDoS攻击
- 错误处理:捕获所有异常
- 头部验证:检查Host等关键头
- 超时设置:避免僵尸连接
5.2 安全防护
// 设置安全响应头
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'SAMEORIGIN');
res.setHeader('X-XSS-Protection', '1; mode=block');
// 限制请求体大小
const MAX_SIZE = 1 * 1024 * 1024; // 1MB
if(req.headers['content-length'] > MAX_SIZE) {
res.writeHead(413);
return res.end('Payload too large');
}
六、进阶应用
6.1 HTTP客户端
// 发起HTTP请求
const options = {
hostname: 'api.example.com',
port: 28081,
path: '/data',
method: 'GET'
};
const req = http.request(options, (res) => {
console.log(`状态码: ${res.statusCode}`);
res.on('data', (chunk) => {
console.log(`响应数据: ${chunk}`);
});
});
req.on('error', (e) => {
console.error(`请求错误: ${e.message}`);
});
req.end();
6.2 代理服务器实现
http.createServer((clientReq, clientRes) => {
const proxyReq = http.request({
host: 'target-server.com',
port: 80,
path: clientReq.url,
method: clientReq.method,
headers: clientReq.headers
}, (proxyRes) => {
clientRes.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(clientRes);
});
clientReq.pipe(proxyReq);
}).listen(8080);
如有疑问, 请参考一下链接:
Node.js官方HTTP文档
HTTP/2模块使用指南
Web安全最佳实践
如何基于HTTP模块实现WebSocket协议?在微服务架构中,HTTP模块可以发挥哪些作用?欢迎在评论区分享你的见解!