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 来加密通信,防止数据被窃听或篡改。
相关推荐
前端付豪2 小时前
必知Node应用性能提升及API test 接口测试
前端·react.js·node.js
王同学 学出来2 小时前
vue+nodejs项目在服务器实现docker部署
服务器·前端·vue.js·docker·node.js
源猿人3 小时前
使用 Node.js 批量下载全国行政区 GeoJSON(含省级 + 地级市)
node.js
_Kayo_5 小时前
Node.JS 学习笔记7
笔记·学习·node.js
程序员爱钓鱼7 小时前
Node.js 编程实战:博客系统 —— 用户注册登录与文章管理
前端·后端·node.js
JaredYe8 小时前
用 Node.js 从旧版 PPT 中提取文本:轻量开源工具 ppt-to-text
node.js·powerpoint·ppt
TDengine (老段)8 小时前
TDengine Node.js 语言连接器入门指南
大数据·开发语言·物联网·node.js·vim·时序数据库·tdengine
余道各努力,千里自同风8 小时前
node.js 操作 MongoDB
数据库·mongodb·node.js
爱敲代码的婷婷婷.8 小时前
patch-package 修改 node_modules流程以及注意点
前端·react native·前端框架·node.js
一念一花一世界8 小时前
Arbess项目实战 - 基于GitLab搭建Node.js项目自动化流水线
ci/cd·node.js·自动化·gitlab·arbess