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

相关推荐
李纲明3 小时前
WordPress 挂上 Cloudflare 后询盘和后台异常:缓存规则、SSL 模式和真实 IP 怎么核
运维·缓存·https·cdn·wordpress·cloudflare
编程的一拳超人3 小时前
【元宝搜索开发者征文大赛】四语实战:Java/Python/Go/Node.js 构建 AI 搜索应用全攻略
java·python·golang·node.js·agent
lucas_AI3 小时前
今年 2 月就修好的漏洞,10 月才炸:HTTP2Shell 把 Node、Python 一锅端
node.js
2501_9151063220 小时前
跨平台抓包工具怎么选?TraceEagle抓包鹰 的四种跨平台能力
网络协议·计算机网络·网络安全·ios·adb·https·udp
j7~1 天前
【Linux网络加餐】《HTTPS 协议原理》---详解
网络·网络协议·https·加密·ca认证·解密
紧跟先前的步伐1 天前
Go AI Agent 实战 12|HTTP 状态码、API 错误处理与日志
开发语言·人工智能·http·ai·golang
SEO_juper1 天前
Node.js 全站死链检测工具:从 sitemap 出发一次找全 404
开发语言·人工智能·python·node.js·seo·外贸独立站
Lsetea1 天前
curl下载HTTPS正文是乱码:--compressed与Content-Encoding分层排查
linux·http·https·ssl证书·curl
刘胡子大叔1 天前
curl resolve 和 Host 头的两种免 DNS 验证 HTTPS
网络协议·http·https
j7~1 天前
【Linux网络加餐】《HTTP 会话保持:Cookie 与 Session 原理及实验验证》---详解
linux·网络·网络协议·http·cookie·session