使用 nodejs 开启 HTTPS 443端口服务

该代码示例展示了如何使用NodeJS的https模块和http-proxy库创建一个HTTPS服务器,监听443端口。通过读取本地证书文件进行安全配置。服务启动后,特定URL返回配置成功或失败的信息,其他请求将被代理到http://0.0.0.0:8083/。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用 nodejs 开启 HTTPS 443端口服务

工具类代码如下:
proxyUtils

const https = require('https');
const httpProxy = require('http-proxy');
const fs = require("fs");
const Path = require("path");
const {execSync} = require('child_process');
const process = require("process");

const proxy = httpProxy.createProxyServer();

// 证书配置,通过 KeyManager 生成开发证书。
const options = {
    key: fs.readFileSync(Path.join(process.cwd(), './data/crt/127.0.0.1_key.key')),
    cert: fs.readFileSync(Path.join(process.cwd(), './data/crt/127.0.0.1_chain.crt')),
};

/**
 * 创建https服务器
 * @returns {Promise<unknown>}
 */
function createHttpsServer() {
    return new Promise((resolve, reject) => {
        try {
            // 用于杀死占用443端口的进程的命令
            const killCmd = 'FOR /F "tokens=5" %P IN (\'netstat -a -n -o ^| findstr :443 ^| findstr /I LISTENING\') DO TaskKill.exe /PID %P /F';
            // 执行命令并等待其完成
            try {
                execSync(killCmd);
            } catch (err) {
            }
            https.createServer(options, (req, res) => {
                if (req.url && (req.url + '').includes('/myCheck')) {
                    // 直接返回文本
                    res.writeHead(200, {'Content-Type': 'application/json'});
                    res.end(JSON.stringify({
                        "消息": "看到我就说明配置成功了!",
                    }, null, 4));
                } else if (req.url && (req.url + '').includes('/myError')) {
                    // 直接返回文本
                    res.writeHead(200, {'Content-Type': 'application/json'});
                    res.end(JSON.stringify({
                        "消息": "配置失败!",
                    }, null, 4));
                } else {
                    proxy.web(req, res, {target: 'http://0.0.0.0:8083/'});
                }
            }).listen(443);
            console.log('https服务器启动成功!');
            resolve();
        } catch (e) {
            console.log('https服务器启动失败!');
            reject(e);
        }
    });
}


module.exports = {
    createHttpsServer
}

// 测试代码
createHttpsServer();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TimBL

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值