HTTP和HTTPS模块

一、HTTP 模块

1. 创建 HTTP 服务器

基本服务器示例
复制代码
const http = require('http');

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(3000, '127.0.0.1', () => {
  console.log('Server running at http://127.0.0.1:3000/');
});
请求对象 (http.IncomingMessage)
  • req.method: HTTP 请求方法 (GET, POST 等)

  • req.url: 请求的 URL 路径

  • req.headers: 请求头对象

  • req.on('data', chunk => {}): 接收请求体数据

  • req.on('end', () => {}): 请求体接收完成

响应对象 (http.ServerResponse)
  • res.statusCode: 设置状态码

  • res.setHeader(name, value): 设置响应头

  • res.writeHead(statusCode, headers): 组合设置状态码和头

  • res.write(data): 写入响应体

  • res.end([data]): 结束响应

2. 发起 HTTP 请求

使用 http.request()
复制代码
const options = {
  hostname: 'example.com',
  port: 80,
  path: '/api/data',
  method: 'GET',
  headers: {
    'Content-Type': 'application/json'
  }
};

const req = http.request(options, (res) => {
  let data = '';
  
  res.on('data', (chunk) => {
    data += chunk;
  });
  
  res.on('end', () => {
    console.log(JSON.parse(data));
  });
});

req.on('error', (error) => {
  console.error(error);
});

req.end();
简化方法 http.get()
复制代码
http.get('http://example.com/api/data', (res) => {
  // 处理响应...
});

二、HTTPS 模块

1. 创建 HTTPS 服务器

基本服务器示例
复制代码
const https = require('https');
const fs = require('fs');

const options = {
  key: fs.readFileSync('server-key.pem'),
  cert: fs.readFileSync('server-cert.pem')
};

const server = https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end('Secure Hello World\n');
});

server.listen(443, () => {
  console.log('HTTPS server running on port 443');
});
证书要求
  • key: 私钥文件

  • cert: 公钥证书

  • 可选 ca: 证书颁发机构链

2. 发起 HTTPS 请求

使用 https.request()
复制代码
const options = {
  hostname: 'api.example.com',
  port: 443,
  path: '/secure-data',
  method: 'GET',
  // 如需验证特定证书可添加以下选项
  // ca: fs.readFileSync('ca-cert.pem'),
  // rejectUnauthorized: true
};

const req = https.request(options, (res) => {
  // 处理响应...
});

req.end();
简化方法 https.get()
复制代码
https.get('https://api.example.com/secure-data', (res) => {
  // 处理响应...
});

三、核心区别与特性对比

特性 HTTP 模块 HTTPS 模块
协议 HTTP HTTPS
默认端口 80 443
安全性 明文传输 SSL/TLS 加密
性能开销 较低 较高 (加密/解密开销)
证书要求 不需要 需要服务器证书
创建服务器 http.createServer() https.createServer(options)
客户端请求 http.request()/http.get() https.request()/https.get()

四、高级特性

1. 代理服务器实现

复制代码
http.createServer((clientReq, clientRes) => {
  const options = {
    hostname: 'target.server.com',
    port: 80,
    path: clientReq.url,
    method: clientReq.method,
    headers: clientReq.headers
  };

  const proxy = http.request(options, (targetRes) => {
    clientRes.writeHead(targetRes.statusCode, targetRes.headers);
    targetRes.pipe(clientRes);
  });
  
  clientReq.pipe(proxy);
}).listen(8080);

2. 处理文件上传

复制代码
const server = http.createServer((req, res) => {
  if (req.method === 'POST' && req.url === '/upload') {
    const fileData = [];
    req.on('data', chunk => {
      fileData.push(chunk);
    });
    req.on('end', () => {
      const buffer = Buffer.concat(fileData);
      fs.writeFile('uploaded.file', buffer, (err) => {
        res.end(err ? 'Upload failed' : 'Upload successful');
      });
    });
  }
});

3. 连接超时处理

复制代码
const request = https.request(options, response => {
  // 正常处理...
});

request.setTimeout(5000, () => {
  request.abort();
  console.log('Request timed out');
});

request.on('error', err => {
  if (err.code === 'ECONNRESET') {
    console.log('Timeout caused connection reset');
  }
});

五、最佳实践

1. 安全实践

  • 始终验证 HTTPS 证书 (生产环境设置 rejectUnauthorized: true)

  • 限制请求头大小防止内存耗尽

  • 使用最新 TLS 版本 (在 Node.js 中通过 secureProtocol 选项)

  • 正确处理连接终止和超时

2. 性能优化

  • 重用 TCP 连接 (Keep-Alive)

  • 使用流式处理大文件

  • 合理设置并发连接数

  • 启用压缩 (通过 Accept-Encoding 头)

3. 错误处理

复制代码
const server = http.createServer((req, res) => {
  // ...处理逻辑
});

server.on('clientError', (err, socket) => {
  if (err.code === 'ECONNRESET' || !socket.writable) return;
  socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});

process.on('uncaughtException', (err) => {
  console.error('Uncaught exception:', err);
  // 优雅关闭服务器
  server.close(() => process.exit(1));
});

六、实际应用场景

1. Web 应用服务器

  • 结合 Express/Koa 等框架

  • 实现 RESTful API

  • 处理静态文件服务

2. 微服务通信

  • 服务间 HTTP 调用

  • 健康检查端点

  • 服务发现集成

3. 代理和网关

  • 反向代理实现

  • API 网关路由

  • 请求/响应转换

4. Webhook 接收

  • 处理第三方服务回调

  • 实时事件通知

  • 数据同步端点

Node.js 的 http 和 https 模块提供了构建网络应用的基础能力,理解它们的核心原理和特性对于开发高性能、安全的网络服务至关重要。在实际项目中,通常会结合上层框架使用,但底层原理仍然基于这些核心模块。

相关推荐
xd0000231 分钟前
11. vue pinia 和react redux、jotai对比
node.js
程序猿小D1 小时前
第16节 Node.js 文件系统
linux·服务器·前端·node.js·编辑器·vim
midsummer_woo2 小时前
【2025年】解决Burpsuite抓不到https包的问题
网络协议·http·https
前端老六喔10 小时前
🎉 开源项目推荐 | 让你的 TypeScript/React 项目瘦身更简单!
node.js·前端工程化
猫头虎10 小时前
[特殊字符]解决 “IDEA 登录失败。不支持早于 14.0 的 GitLab 版本” 问题的几种方法
java·ide·网络协议·http·https·gitlab·intellij-idea
醉书生ꦿ℘゜এ10 小时前
npm error Cannot read properties of null (reading ‘matches‘)
前端·npm·node.js
扣丁梦想家11 小时前
✅ 常用 Java HTTP 客户端汇总及使用示例
java·开发语言·http
超级土豆粉11 小时前
从0到1写一个适用于Node.js的User Agent生成库
linux·ubuntu·node.js
2501_9160074713 小时前
绕过 Xcode?使用 Appuploader和主流工具实现 iOS 上架自动化
websocket·网络协议·tcp/ip·http·网络安全·https·udp
2501_9160137413 小时前
使用 Windows 完成 iOS 应用上架:Appuploader对比其他证书与上传方案
websocket·网络协议·tcp/ip·http·网络安全·https·udp