推荐答案
// www.javascriptcn.com code example
const https = require('https');
const fs = require('fs');
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);
res.end('Hello, HTTPS!');
});
server.listen(443, () => {
console.log('HTTPS server running on port 443');
});本题详细解读
1. 引入必要的模块
首先,我们需要引入 https 和 fs 模块。https 模块用于创建 HTTPS 服务器,而 fs 模块用于读取 SSL 证书和私钥文件。
const https = require('https');
const fs = require('fs');2. 配置 SSL 选项
为了创建一个 HTTPS 服务器,我们需要提供 SSL 证书和私钥。这些文件通常以 .pem 格式存储。使用 fs.readFileSync 方法读取这些文件,并将它们作为 options 对象的 key 和 cert 属性。
const options = {
key: fs.readFileSync('path/to/private-key.pem'),
cert: fs.readFileSync('path/to/certificate.pem')
};3. 创建 HTTPS 服务器
使用 https.createServer 方法创建 HTTPS 服务器。该方法接受两个参数:options 对象和一个请求处理函数。请求处理函数会在每次有请求到达时被调用。
const server = https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('Hello, HTTPS!');
});4. 启动服务器
最后,使用 server.listen 方法启动服务器,并指定监听的端口号(通常 HTTPS 使用 443 端口)。
server.listen(443, () => {
console.log('HTTPS server running on port 443');
});通过以上步骤,你就可以使用 Node.js 的 http 模块实现一个简单的 HTTPS 服务器。