/*
{
Agent: [Function: Agent],
globalAgent: Agent {
_events: [Object: null prototype] {
free: [Function (anonymous)],
newListener: [Function: maybeEnableKeylog]
},
_eventsCount: 2,
_maxListeners: undefined,
defaultPort: 443,
protocol: 'https:',
options: [Object: null prototype] { noDelay: true, path: null },
requests: [Object: null prototype] {},
sockets: [Object: null prototype] {},
freeSockets: [Object: null prototype] {},
keepAliveMsecs: 1000,
keepAlive: false,
maxSockets: Infinity,
maxFreeSockets: 256,
scheduling: 'lifo',
maxTotalSockets: Infinity,
totalSocketCount: 0,
maxCachedSessions: 100,
_sessionCache: { map: {}, list: [] },
[Symbol(kCapture)]: false
},
Server: [Function: Server],
createServer: [Function: createServer],
get: [Function: get],
request: [Function: request]
}
*/
const https = require('node:https')
console.log(https)
1.Agent
https.Agent
是 Node.js https
模块中的一个类,用于管理连接的持久性和性能。
https.Agent
的作用:
- 连接复用:通过复用现有的连接,
Agent
可以减少创建新连接所需的开销,特别是在发送多个请求到同一个服务器时。 - 连接池管理:
Agent
会维护一个连接池,允许您控制最大并发连接数、空闲连接超时时间等参数。 - 代理设置:您可以配置代理服务器,并通过
Agent
管理请求的代理行为。
https.Agent
的常见属性和方法:
new https.Agent([options])
: 创建一个新的Agent
实例。options
可以包含以下属性:
- `keepAlive`: 是否启用连接保持活动状态(默认:`false`)。
- `keepAliveMsecs`: 在启用 `keepAlive` 时,保持空闲连接的空闲时间(默认:`1000` 毫秒)。
- `maxSockets`: 每个主机的最大并发连接数(默认:`Infinity`)。
- `maxFreeSockets`: 最大空闲连接数(默认:`256`)。
agent.destroy()
: 销毁所有现有的套接字并阻止新的请求。agent.getName(options)
: 返回一个字符串,该字符串用于标识给定的连接参数,以便在连接池中查找或创建连接。
const https = require('https')
// 创建一个 Agent 实例
const agent = new https.Agent({
keepAlive: true,
maxSockets: 10,
maxFreeSockets: 5,
keepAliveMsecs: 10000
})
// 使用 agent 发起请求
https.get('https://example.com', { agent: agent }, (res) => {
let data = ''
res.on('data', (chunk) => {
data += chunk
})
res.on('end', () => {
console.log(data)
})
}).on('error', (err) => {
console.error('Error: ' + err.message)
})
2.globalAgent
https.globalAgent
是 Node.js https
模块中的一个全局 Agent
实例,它用于处理所有没有显式指定 Agent
的 HTTPS
请求。
这意味着,当你在发起 HTTPS
请求时,如果没有为该请求提供一个自定义的 Agent
实例,Node.js
会自动使用 https.globalAgent
来管理连接。
如果想全局配置 HTTPS
连接的行为,比如启用 keepAlive
以保持连接的持久性,可以直接修改 https.globalAgent
的配置:
const https = require('https')
// 配置 https.globalAgent
https.globalAgent.keepAlive = true
https.globalAgent.maxSockets = 100 // 限制最大并发连接数
// 发起请求,不指定 Agent,因此会使用 https.globalAgent
https.get('https://example.com', (res) => {
let data = ''
res.on('data', (chunk) => {
data += chunk
})
res.on('end', () => {
console.log(data)
})
}).on('error', (err) => {
console.error('Error: ' + err.message)
})
3.Server
https.Server
是 Node.js https
模块中的一个类,用于创建 HTTPS
服务器。
与 http.Server
类似,https.Server
使得你能够监听和处理来自客户端的 HTTP
请求,但它是通过加密的 TLS/SSL
协议进行的,从而确保通信的安全性。
要创建一个 HTTPS
服务器,需要提供 TLS/SSL
证书和密钥,然后使用 https.createServer()
方法来生成一个 https.Server
实例。
const https = require('https')
const fs = require('fs')
// 读取 SSL/TLS 证书和密钥
const options = {
key: fs.readFileSync('path/to/server-key.pem'),
cert: fs.readFileSync('path/to/server-cert.pem')
}
// 创建 HTTPS 服务器
const server = https.createServer(options, (req, res) => {
res.writeHead(200)
res.end('Hello, Secure World!')
})
// 监听指定端口
server.listen(443, () => {
console.log('HTTPS server is running on port 443')
})
4.createServer
https.createServer
是 Node.js
中用于创建 HTTPS
服务器的方法。
options
对象:
包含 key
和 cert
属性,这些属性分别是私钥和证书文件路径。
这些文件通常以 .key
和 .crt
或 .pem
扩展名保存。
const https = require('https')
const fs = require('fs')
const path = require('node:path')
// 读取证书和私钥文件
const options = {
key: fs.readFileSync(path.resolve(__dirname, './key-cert/key.pem'), 'utf8'),
cert: fs.readFileSync(path.resolve(__dirname, './key-cert/cert.pem'), 'utf8')
}
// 创建 HTTPS 服务器
const server = https.createServer(options, (req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('Hello, world!\n')
})
// 监听端口
server.listen(443, () => {
console.log('HTTPS server is running on port 443')
console.log('https://localhost:443')
})
5.get
https.get
是 Node.js
中用于发起 HTTPS GET
请求的简便方法。
它类似于 https.request
,但专门用于发送 GET
请求,并且不需要手动调用 req.end()
来结束请求。
const https = require('https')
// 请求选项
const options = {
hostname: 'jsonplaceholder.typicode.com',
port: 443,
path: '/posts/1',
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
// 发起请求
https.get(options, (res) => {
let data = ''
res.on('data', (chunk) => {
data += chunk
})
res.on('end', () => {
console.log('Response:', data)
})
}).on('error', (e) => {
console.error('Request error:', e)
})
6.request
https.request
是 Node.js
中用于发起 HTTPS
请求的方法。
它用于向 HTTPS
服务器发送请求,并接收响应。
const https = require('https')
// 请求选项
const options = {
hostname: 'example.com',
port: 443, // 默认端口,通常不需要指定
path: '/path',
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
// 发起请求
const req = https.request(options, (res) => {
let data = ''
// 接收数据
res.on('data', (chunk) => {
data += chunk
})
// 请求结束
res.on('end', () => {
console.log('Response:', data)
})
})
// 处理请求错误
req.on('error', (e) => {
console.error('Request error:', e)
})
// 发送请求
req.end()
ps.openssl创建自签名证书
# 2048位私钥
openssl genrsa -out ./scripts/25.https/key-cert/key.pem 2048
# 根据私钥生成证书签名请求 Certificate Signing Request
# -new: 生成新的证书签名请求
# -key: 指定私钥
# -out: 指定输出文件
openssl req -new -key ./scripts/25.https/key-cert/key.pem -out ./scripts/25.https/key-cert/csr.pem
# 生成自签名证书
# -req: 指定证书签名请求文件
# -days: 指定证书有效期
# -in: 指定证书签名请求文件
# -signkey: 指定私钥
# -out: 指定输出文件
openssl x509 -req -days 365 -in ./scripts/25.https/key-cert/csr.pem -signkey ./scripts/25.https/key-cert/key.pem -out ./scripts/25.https/key-cert/cert.pem