node.js内置模块之---http 和 https 模块

http 和 https 模块的作用

Node.js 中,httphttps 模块用于创建和处理 HTTP 和 HTTPS 请求/响应

http模块

http 模块提供了用于实现 HTTP 协议的功能。它可以用来创建 HTTP 服务器,处理 HTTP 请求,发送 HTTP 响应,同时也可以用来发送 HTTP 客户端请求。

创建 HTTP 服务器

使用 http.createServer() 方法可以创建一个 HTTP 服务器,该服务器可以监听 HTTP 请求并返回响应。

javascript 复制代码
const http = require('http');

// 创建一个 HTTP 服务器
const server = http.createServer((req, res) => {
  // 设置响应头
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  
  // 返回响应
  res.end('Hello, HTTP!');
});

// 监听 3000 端口
server.listen(3000, () => {
  console.log('Server is running at http://localhost:3000');
});
  • req: 请求对象,包含有关客户端请求的信息(例如 URL、请求头、查询参数等)。
  • res: 响应对象,用来发送响应给客户端。通过 res.writeHead() 设置 HTTP 状态码和响应头,使用 res.end() 发送响应数据。
处理 HTTP 请求

可以使用 req 对象来处理请求,获取请求的相关信息。

javascript 复制代码
const http = require('http');

const server = http.createServer((req, res) => {
  // 获取请求方法(GET, POST 等)
  const method = req.method;
  
  // 获取请求的 URL
  const url = req.url;
  
  console.log(`Method: ${method}, URL: ${url}`);
  
  // 响应处理
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Request received');
});

server.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});
发送 HTTP 请求

使用 http.request() 方法可以发送 HTTP 请求。这可以用于与其他 HTTP 服务进行通信。

javascript 复制代码
const http = require('http');

const options = {
  hostname: 'example.com',
  port: 80, // 默认的 HTTP 端口
  path: '/',
  method: 'GET'
};

const req = http.request(options, (res) => {
  let data = '';

  res.on('data', (chunk) => {
    data += chunk;
  });

  res.on('end', () => {
    console.log(data);
  });
});

req.on('error', (e) => {
  console.error(`Problem with request: ${e.message}`);
});

req.end();
  • options: 请求的配置,包括目标服务器的地址、端口、请求方法等。
  • res: 响应对象,用于处理服务器的响应数据。

https 模块

https 模块提供了与 http 模块类似的功能,但它使用 SSL/TLS 加密 来保证数据传输的安全性。通常在涉及到敏感数据(如用户名、密码、支付信息等)的应用中,需要使用 HTTPS 来加密通信。

创建 HTTPS 服务器

与 HTTP 服务器类似,HTTPS 服务器需要提供 SSL/TLS 证书(公钥和私钥),以便在建立连接时加密通信。

javascript 复制代码
const https = require('https');
const fs = require('fs');

// 读取 SSL 证书和私钥
const options = {
  key: fs.readFileSync('path/to/private-key.pem'),
  cert: fs.readFileSync('path/to/certificate.pem')
};

const server = https.createServer(options, (req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello, HTTPS!');
});

server.listen(3000, () => {
  console.log('HTTPS server is running on https://localhost:3000');
});
  • key: 私钥文件(通常是 .pem 格式)。
  • cert: 公钥证书文件(通常是 .pem 格式)。
  • options:这些选项用于配置加密通信。
发送 HTTPS 请求

HTTPS 客户端请求与 HTTP 相似,区别在于使用 https.request() 发送加密请求。

javascript 复制代码
const https = require('https');

const options = {
  hostname: 'example.com',
  port: 443,  // 默认的 HTTPS 端口
  path: '/',
  method: 'GET'
};

const req = https.request(options, (res) => {
  let data = '';

  res.on('data', (chunk) => {
    data += chunk;
  });

  res.on('end', () => {
    console.log(data);
  });
});

req.on('error', (e) => {
  console.error(`Problem with request: ${e.message}`);
});

req.end();

httphttps 模块的区别

特性 http 模块 https 模块
协议 非加密的 HTTP 协议 加密的 HTTPS 协议
端口 默认使用端口 80 默认使用端口 443
安全性 不加密数据,容易遭受中间人攻击 加密通信,保护数据隐私
证书 不需要证书 需要 SSL/TLS 证书
应用场景 公共内容、测试环境 需要保护用户数据的应用(如银行、支付系统)

使用 httpshttp 模块时的注意事项

  • 证书 :使用 https 时,必须提供有效的 SSL/TLS 证书。可以通过自签名证书进行开发,但生产环境必须使用可信的证书(例如来自 Let's Encrypt、VeriSign 等)。
  • 性能https 通常比 http 稍慢,因为它涉及到加密/解密操作。在不需要加密的场景下,尽量使用 http
  • 安全:在生产环境中,尤其是涉及敏感信息的情况下,必须使用 HTTPS 来加密通信,防止数据被窃听或篡改。
相关推荐
前端老六喔1 小时前
🎉 开源项目推荐 | 让你的 TypeScript/React 项目瘦身更简单!
node.js·前端工程化
醉书生ꦿ℘゜এ1 小时前
npm error Cannot read properties of null (reading ‘matches‘)
前端·npm·node.js
超级土豆粉2 小时前
从0到1写一个适用于Node.js的User Agent生成库
linux·ubuntu·node.js
空中湖5 小时前
‘pnpm‘ 不是内部或外部命令,也不是可运行的程序
npm·node.js
SailingCoder6 小时前
grafana-mcp-analyzer:基于 MCP 的轻量 AI 分析监控图表的运维神器!
运维·人工智能·typescript·node.js·grafana
又又呢9 小时前
前端面试题总结——webpack篇
前端·webpack·node.js
avoidaily17 小时前
使用Node.js分片上传大文件到阿里云OSS
阿里云·node.js·云计算
xd0000217 小时前
8.axios Http网络请求库(1)
node.js
孟孟~17 小时前
npm run dev 报错:Error: error:0308010C:digital envelope routines::unsupported
前端·npm·node.js
孟孟~17 小时前
npm install 报错:npm error: ...node_modules\deasync npm error command failed
前端·npm·node.js