1. Node.js 中的网络模块(http
和 https
)
原理与作用:
Node.js 的
http
和https
模块是内置的核心模块,用于创建 HTTP 和 HTTPS 服务器。http
模块基于 Node.js 的事件驱动架构,利用libuv
和HTTP parser
库高效处理 HTTP 请求和响应。https
模块在http
模块的基础上增加了 SSL/TLS 加密功能,用于创建安全的 HTTPS 服务器。
2. 如何创建 HTTP 服务器
基础示例
以下是使用 http
模块创建一个简单 HTTP 服务器的代码示例:
// 引入 http 模块
const http = require('http');
// 创建服务器
const server = http.createServer((req, res) => {
// 设置响应头,指定编码为 UTF-8
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
// 返回响应内容
res.end('欢迎访问我的 Node.js HTTP 服务器!');
});
// 监听端口
const port = 3000;
server.listen(port, () => {
console.log(`服务器已启动,正在监听 http://localhost:${port}`);
});
代码解析
http.createServer()
:创建一个 HTTP 服务器实例,接受一个回调函数作为参数。
回调函数会在每次 HTTP 请求到达时触发,传入
req
(请求对象)和res
(响应对象)。
req
和res
:req
对象包含与传入请求相关的信息(如 URL、HTTP 方法、Headers)。res
对象用于设置响应状态、发送响应数据。
server.listen()
:将服务器绑定到指定的端口和 IP 地址(默认是
localhost
或127.0.0.1
)。
高级示例:支持路由和参数
const http = require('http');
const server = http.createServer((req, res) => {
// 解析请求路径
const url = req.url;
console.log(`请求路径:${url}`);
if (url === '/') {
// 主页
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>首页</h1><p>欢迎访问首页!</p>');
} else if (url === '/about') {
// 关于页面
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>关于我</h1><p>这里是关于我的页面。</p>');
} else {
// 未找到页面
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('<h1>404 - 页面未找到</h1>');
}
});
server.listen(3000, () => {
console.log('服务器已启动,访问 http://localhost:3000');
});
3. 合理化的使用建议
使用模块化开发
将路由、中间件、业务逻辑拆分到不同模块中。
示例:
// routes.js module.exports = { home: (req, res) => res.end('首页内容'), about: (req, res) => res.end('关于页面内容') }; // server.js const http = require('http'); const routes = require('./routes'); const server = http.createServer((req, res) => { switch (req.url) { case '/': routes.home(req, res); break; case '/about': routes.about(req, res); break; default: res.writeHead(404); res.end('未找到页面'); } }); server.listen(3000);
使用中间件
中间件用于在请求处理过程中添加通用逻辑(如日志记录、身份验证)。
示例:
const logRequest = (req, res, next) => { console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`); next(); // 调用下一个中间件或路由处理器 }; const server = http.createServer((req, res) => { logRequest(req, res, () => { // 处理请求逻辑 res.end('Hello Middleware!'); }); });
使用模板引擎(可选)
如
EJS
或Pug
,用于动态生成 HTML 内容。示例(使用 EJS):
const ejs = require('ejs'); const fs = require('fs'); const server = http.createServer(async (req, res) => { const template = await fs.promises.readFile('./template.ejs', 'utf8'); const html = ejs.render(template, { name: 'Alice' }); res.writeHead(200, { 'Content-Type': 'text/html' }); res.end(html); });
4. 实际开发中需要注意的点
错误处理
始终处理所有可能的错误(如文件读取失败、数据库查询失败)。
示例:
fs.readFile('non-existent-file.txt', (err, data) => { if (err) { res.writeHead(500); res.end('文件读取失败'); return; } res.end(data); });
性能优化
使用
gzip
压缩响应数据,减少传输时间。const zlib = require('zlib'); res.writeHead(200, { 'Content-Type': 'text/html', 'Content-Encoding': 'gzip' }); zlib.gzip('<h1>Compressed page</h1>', (err, gzipData) => { res.end(gzipData); });
安全性
使用 HTTPS
const https = require('https'); const fs = require('fs'); const options = { key: fs.readFileSync('server.key'), cert: fs.readFileSync('server.cert') }; https.createServer(options, (req, res) => { res.end('安全的 HTTPS 服务器'); }).listen(443);
防止 XSS 和 CSRF 攻击:
对用户输入进行验证和过滤。
使用安全的头信息(如
Content-Security-Policy
)。
关闭服务器
优雅关闭服务器,确保所有请求处理完成后再退出。
const gracefulShutdown = () => { server.close(() => { console.log('服务器已关闭'); process.exit(0); }); setTimeout(() => { console.error('强制关闭服务器'); process.exit(1); }, 3000); }; process.on('SIGTERM', gracefulShutdown);
5. 总结
http
和https
模块是构建 Node.js 服务的基础,灵活运用它们可以创建功能强大的 HTTP/HTTPS 服务器。开发建议包括模块化、中间件、模板引擎以及安全性、性能优化等。
实际开发中要特别注意错误处理、安全性以及优雅关闭服务器等细节。