首页 > 解决方案 > 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.

标签: node.js

解决方案


我不得不添加

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

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


推荐阅读