Node.js https 模块

Java FileNode.js 内置模块


https 是 Node.js 内置的核心模块,用于创建 HTTPS 服务器和客户端,处理安全的 HTTP 请求和响应。HTTPS 是在 HTTP 基础上通过 SSL/TLS 协议加密的安全传输协议。

http 模块相比,https 模块的主要区别在于:

  • 使用 SSL/TLS 加密通信
  • 默认端口是 443 而非 80
  • 需要数字证书来验证服务器身份

核心功能

创建 HTTPS 服务器

实例

const https = require('https');
const fs = require('fs');

// 读取证书文件
const options = {
  key: fs.readFileSync('server-key.pem'),
  cert: fs.readFileSync('server-cert.pem')
};

// 创建 HTTPS 服务器
const server = https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end('Hello HTTPS World!');
});

server.listen(443, () => {
  console.log('HTTPS server running on port 443');
});

发起 HTTPS 请求

实例

const https = require('https');

https.get('https://example.com', (res) => {
  console.log('状态码:', res.statusCode);
  console.log('请求头:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
}).on('error', (e) => {
  console.error(e);
});

关键概念

SSL/TLS 证书

HTTPS 服务器需要以下证书文件:

  • key: 私钥文件(.key 或 .pem)
  • cert: 公钥证书(.crt 或 .pem)
  • 可选 ca: 证书颁发机构(CA)的中间证书

可以使用 OpenSSL 生成自签名证书用于开发测试:

实例

openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365

请求和响应

https 模块的 API 与 http 模块几乎相同,主要对象包括:

  • https.Server: HTTPS 服务器类
  • https.request(): 发起 HTTPS 请求
  • https.get(): 发起 GET 请求的快捷方法

实际应用场景

  1. 安全 Web 服务:构建需要加密传输的 Web 应用
  2. API 调用:安全地调用第三方 HTTPS API
  3. 微服务通信:服务间安全通信
  4. 代理服务器:构建安全的代理服务

安全最佳实践

  1. 始终使用 HTTPS 而非 HTTP 传输敏感数据
  2. 定期更新 SSL/TLS 证书
  3. 使用强密码套件和安全协议版本
  4. 考虑使用 Let's Encrypt 等免费证书颁发机构
  5. 在生产环境中避免使用自签名证书

通过 https 模块,Node.js 开发者可以轻松构建安全的网络应用和服务,保护数据传输过程中的隐私和完整性。

Java FileNode.js 内置模块