Skip to content
/ NodeRaw/node:https
9/9/2024
1m
AI 摘要

本文介绍了如何使用 Node.js 创建基于 HTTPS 协议的服务器,重点包括使用 mkcert 生成证书和私钥,并通过 https.createServer 方法配置和启动服务。

node:https

创建一个基于 HTTPS 协议的服务器

创建一个本地的 https 服务

使用 mkcert 创建 cert 证书和 private key 文件:

$ mkcert localhost

然后创建一个 https 服务器:

import https from 'https';
import fs from 'fs';

const options = {
    key: fs.readFileSync('./localhost-key.pem'),
    cert: fs.readFileSync('./localhost.pem'),
}

https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end('Hello, HTTPS World!');
}).listen(443, () => {
  console.log('Server is running on port 443');
});

Released under the MIT License.