【问题标题】:Nodejs Express https to http redirect not workingNodejs Express https到http重定向不起作用
【发布时间】:2020-04-23 00:37:18
【问题描述】:

我在我的 Nodejs 服务器上安装了 SSL 证书。

const fs = require('fs');
const https = require('https');
const app = require('express');

https.createServer({
    key: fs.readFileSync('./ssl/private.key'),
    ca:fs.readFileSync('./ssl/ca_bundle.crt'),
    cert: fs.readFileSync('./ssl/certificate.crt')
}, app).listen(443);

443端口是https的默认监听端口,8080端口是http的默认监听端口。我的服务器工作正常,我可以通过https://www.example.net 访问我的网站。但是如果我删除 https 或将其替换为 http ,我希望我的服务器自动重定向到 https 所以我添加了:

app.use (function (req, res, next) {
    if (req.secure) {
            // request was via https, so do no special handling
            console.log(`Secure request`)
            next();
    } else {
            // request was via http, so redirect to https
            console.log(`Unsecure request`)
            res.redirect('https://' + req.headers.host + req.url);
    }
});

我仍然可以使用 https 连接文件,但如果我删除它,我会得到:

> dial tcp 312.312.d12.213:80: connectex: A connection attempt failed
> because the connected party did not properly respond after a period of
> time, or established connection failed because connected host has
> failed to respond.

【问题讨论】:

  • 这是因为您使用的是 8080 端口而不是 80 端口(浏览器期望的端口),所以它尝试连接到未监听的端口(80 而不是 8080),尝试访问example.net:8080 看看它是如何工作的。
  • 另外,证书和重定向,不要在node里面做,把nginx放在前面,想法是nodejs应用不需要管理证书或者重定向,只是一个普通的老http rest api。
  • @SebastiánEspinosa 我没有使用端口 8080 我使用的是端口 443,这就是 https 请求有效的原因
  • @SebastiánEspinosa 我将使用 nginx。谢谢你让我知道。目前,如果不使用 nginx,我已经发布了解决方案。

标签: node.js


【解决方案1】:

我必须添加

http.createServer(app).listen(80);

这样它也可以监听不安全的请求

【讨论】:

  • 只是另一个建议,你永远不想在端口 80 上直接运行服务,因为这是一个保留端口,所以你将使用管理员权限运行它,所以你的服务也有管理员权限,这意味着如果有人可以向您的应用程序注入代码,它将具有 root 权限,只是想提供帮助。
猜你喜欢
  • 2023-03-22
  • 2014-03-10
  • 2018-06-11
  • 2015-07-28
  • 2018-02-11
  • 2022-01-14
  • 2021-04-15
  • 2018-01-31
  • 1970-01-01
相关资源
最近更新 更多