推荐答案
使用 https 模块创建 HTTPS 服务器
// www.javascriptcn.com code example
const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem')
};
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('Hello, HTTPS!');
}).listen(443);使用 https 模块创建 HTTPS 客户端
// www.javascriptcn.com code example
const https = require('https');
https.get('https://example.com', (res) => {
console.log('statusCode:', res.statusCode);
res.on('data', (d) => {
process.stdout.write(d);
});
}).on('error', (e) => {
console.error(e);
});本题详细解读
https 模块的作用
https 模块是 Node.js 内置的一个模块,用于处理 HTTPS 协议。它基于 http 模块,但在底层使用了 TLS/SSL 加密,确保数据在传输过程中的安全性。https 模块可以用于创建 HTTPS 服务器和客户端,适用于需要加密通信的场景,如处理敏感数据的 Web 应用。
创建 HTTPS 服务器
要创建一个 HTTPS 服务器,首先需要生成或获取 SSL/TLS 证书和私钥。通常,这些文件以 .pem 或 .crt 格式存储。然后,使用 https.createServer() 方法创建服务器,传入包含 key 和 cert 的选项对象。key 是私钥文件的内容,cert 是证书文件的内容。
const options = {
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem')
};创建服务器后,可以像处理 HTTP 请求一样处理 HTTPS 请求。
创建 HTTPS 客户端
https 模块还提供了 https.get() 和 https.request() 方法,用于向其他 HTTPS 服务器发送请求。https.get() 是一个简化版的 https.request(),专门用于发送 GET 请求。
https.get('https://example.com', (res) => {
console.log('statusCode:', res.statusCode);
res.on('data', (d) => {
process.stdout.write(d);
});
}).on('error', (e) => {
console.error(e);
});在这个例子中,https.get() 向 https://example.com 发送一个 GET 请求,并在收到响应时打印状态码和响应体。