正确的方式来监听NodeJS中的HTTP和HTTPS

我想在我的NodeJS应用程序中同时提供HTTP和HTTPS。 这是内部应用程序,有些访问者不支持HTTPS。

这是简单的正确方法,还是应该是2个独立的NodeJS应用程序?

http.createServer(app).listen(80, function () { console.log('My insecure site'); }); https.createServer(options, app).listen(443, function () { console.log('My sdecure site'); }); 

我不认为有更好的办法。 您可以做更多的优化,因为HTTP和HTTPS服务器都做同样的事情。 创build一个名为register的函数来configuration中间件和路由。 然后,只需为HTTP和HTTPS调用它。

 var register = function (app) { // config middleware app.configure({ }); // config routes app.get(...); }; var http = express.createServer(); register(http); http.listen(80); var https = express.createServer(); register(https); https.listen(443);