gpt4 book ai didi

node.js - 使用 Express 的多个证书/虚拟主机

转载 作者:搜寻专家 更新时间:2023-11-01 00:40:25 25 4
gpt4 key购买 nike

我在 Cody-CMS 中使用 Express + vhost 将 nodejs 与多个主机一起使用了一段时间。现在我还想包括虚拟 https 服务器。

SNICallback 被调用,但它到此为止......我的 Express 应用程序“exp”从未被调用(即使我在 createServer 中用一个简单的函数替换它也没有——在注释中)。我收到“请求:site1.com”(或 site2.com),但没有任何内容返回到浏览器。

对于 http 服务器,它工作完美。

欢迎任何帮助。

"use strict";

var express = require("express");
var vhost = require("vhost");
var fs = require("fs");


var app1 = express();
app1.all("/", function(req, res) {
res.send('Hello World, site #1');
});

var app2 = express();
app2.all("/", function(req, res) {
res.send('Hello World, site #2');
});


//////////////////
// certificates //
//////////////////
var crypto = require('crypto');

const site1 = {
app: app1,
context: crypto.createCredentials({
key: fs.readFileSync('ws.key').toString(),
cert: fs.readFileSync('ws.crt').toString()
}).context

};
const site2 = {
app: app2,
context: crypto.createCredentials({
key: fs.readFileSync('ws2.key').toString(),
cert: fs.readFileSync('ws2.crt').toString()
}).context
};

var sites = {
"www.site1.com": site1,
"site1.com": site1,

"www.site2.com": site2,
"site2.com": site2
};

// put (www.)site1/2.com in /etc/hosts to 127.0.0.1



//////////
// http //
//////////

var exp = express();
for (let s in sites) {
console.log("http -> " + s);
exp.use(vhost(s, sites[s].app));
}

exp.listen(80, function () {
console.log("Listening https on port: 80")
});


///////////
// https //
///////////

var secureOpts = {
SNICallback: function (domain) {
console.log('request for: ', domain);
return sites[domain].context;
},
key: fs.readFileSync('ws.key').toString(),
cert: fs.readFileSync('ws.crt').toString()
};


var https = require('https');
var httpsServer = https.createServer(secureOpts, exp);
// var httpsServer = https.createServer(secureOpts, function(req, resp) { resp.send("hello"); });

httpsServer.listen(443, function () {
console.log("Listening https on port: 443")
});

最佳答案

SNICallback 有第二个参数:cbcb 的签名为(error, context)。所以你的 secureOpts 应该是这样的:

var secureOpts = {
SNICallback: function(domain, cb) {
console.log('request for: ', domain);
cb(null, sites[domain].context);
},
key: fs.readFileSync('ws.key').toString(),
cert: fs.readFileSync('ws.crt').toString()
};

关于node.js - 使用 Express 的多个证书/虚拟主机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36462396/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com