【问题标题】:nodejs https.createServer not working on http:// with custom portnodejs https.createServer 无法使用自定义端口在 http:// 上工作
【发布时间】:2020-02-04 12:11:24
【问题描述】:

我使用 https.createServer 创建一个安全连接服务器,但是,它不适用于我的自定义端口 http://localhost:2019

以下是我的代码:

const options = {
    key:fs.readFileSync('security/privkey1.pem'),
    cert:fs.readFileSync('security/cert1.pem')
}
const app = express()
const https = require('https').createServer(options, app).listen(2019)

app.use(function(req, res, next) {
    console.log("checking secure connection")
    if(req.secure){
        next();
    }else{
        res.redirect('https://' + req.headers.host + req.url);
    }
});

当我访问https://localhost:2019 时,它可以正常工作,但是当我访问http://localhost:2019 时,它不会到达服务器(控制台没有打印“检查安全连接”)。

Nodejs高手请指教请指教。

谢谢。

【问题讨论】:

  • 由于您已经启动了HTTPS服务器,因此您无法通过HTTP访问该页面,因此服务器会监听HTTPS连接。如果您希望能够同时通过 http:// 和 https:// 访问该页面,那么您需要启动两台服务器,一台使用 http 模块,另一台使用 https。如果你想遵循约定,那么你可以启动 http 服务器并将连接重定向到 https
  • @SebastianKaczmarek 我不能让 http 服务器和 https 服务器同时监听同一个端口,应用程序崩溃了。
  • 所以你必须在同一个端口上监听,对吧?这可能会有所帮助:stackoverflow.com/questions/22453782/…

标签: node.js express https


【解决方案1】:

您正在https、端口2019 上创建服务器。这意味着您可以通过端口 2019 上的 https 访问您的服务器。您可以在另一个端口上创建一个 http 服务器,并将流量从那里重定向到 2019 年的 https。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    • 1970-01-01
    • 1970-01-01
    • 2017-09-12
    • 2015-07-04
    • 2018-04-18
    相关资源
    最近更新 更多