node.js - Nodejs Express https到http重定向不起作用
问题描述
我在我的 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.
解决方案
我不得不添加
http.createServer(app).listen(80);
这样它也可以监听不安全的请求
推荐阅读
- .net - ASPNET Identity 2.0 - UserManager.Update 不适用于某些用户
- c++ - 如何使用移位在 C++ 中的 char 数组中插入整数?
- mongodb - 根据另一个集合字段值设置一个 MongoDB 集合字段值
- html - 当我单击锚标记的 ext 时,它不会将我带到另一个页面
- python - 在 Pandas DataFrame 中创建列的用户输入
- javascript - 在逗号分隔字符串的每个第一个位置插入一个文本元素
- javascript - 无法使用 expo-cli 安装反应原生依赖项
- php - 在登录过程中添加操作
- java - 使用 mvn 函数在本地运行 gcp 云函数:使用 ENV 变量运行
- javascript - 捕获我导出的 async/await 函数的错误