node-red requireHttps 不起作用,访问 http 不会重定向到 https

node-red requireHttps does not work, accessing http does not redirect to https

我正在尝试使用 HTTPS 将节点红色实例公开到互联网,遵循 this tutorial
简而言之,我在 node-red 的 setting.js 中添加(未注释)以下行:

var fs = require("fs");

requireHttps: true,

https: {
       key: fs.readFileSync('privatekey.pem'),
       cert: fs.readFileSync('certificate.pem')
},

https 按预期工作。但是,http 不会重定向到 https,而是给出 ERR_EMPTY_RESPONSE

有人可以帮忙吗? 谢谢

这是按设计工作的,Node-RED 一次只侦听一个端口,因此当配置为使用 HTTPS 时,它不会响应 HTTP 流量。

这意味着您不能仅使用 Node-RED 从一个重定向到另一个。更好的解决方案是使用 nginx 之类的东西来反向代理 Node-RED 并让它处理重定向。

来自您链接到的文章:

Note:I didn’t get this to work with SSL so you may need to skip this

你可以看到作者也弄错了,无法让它工作。 .

无需任何其他网络服务器即可完成这项工作。

基于 Node-RED documentation: Embedding into an existing app,node-RED 运行s 具有由 node.js 提供的托管 http 和 https 服务器。

根据您提供的教程,您不必覆盖 settings.js。

要完成这项工作,您必须创建自己的项目:

$ mkdir myNodeREDProject
$ cd myNodeRedProject
$ touch index.js
$ npm init
$ npm install node-red

将您的 ssl 私钥和证书复制到 myNodeREDProject 文件夹中。

编辑 index.js 并复制以下内容:

const https = require('https');
const express = require("express");
const RED = require("node-red");
const fs = require('fs');

const HTTP_PORT = 8080;
const HTTPS_PORT = 8443;

// Create an Express app
const app = express();

// at the top of routing: this is the http redirection to https part ;-)
app.all('*', (req, res, next) => {
  if (req.protocol === 'https') return next();
  res.redirect(`https://${req.hostname}:${HTTPS_PORT}${req.url}`);
});

// Add a simple route for static content served from 'public'
app.use("/",express.static("public"));

// Create a https server
const options = {
  key: fs.readFileSync('./privatekey.pem'),
  cert: fs.readFileSync('./certificate.pem')
};
const httpsServer = https.createServer(options, app);
// create a http server
const httpServer = http.createServer(app);

// Create the settings object - see default settings.js file for other options
const settings = {
  httpAdminRoot:"/red",
  httpNodeRoot: "/api",
  userDir:"./nodered/",
  functionGlobalContext: { }    // enables global context
};

// Initialise the runtime with a server and settings
RED.init(httpsServer,settings);

// Serve the editor UI from /red
app.use(settings.httpAdminRoot,RED.httpAdmin);

// Serve the http nodes UI from /api
app.use(settings.httpNodeRoot,RED.httpNode);

httpsServer.listen(HTTPS_PORT);
httpServer.listen(HTTP_PORT);

// Start the runtime
RED.start();

最后,运行 node-RED 应用程序:

$ node index.js   # MAGIC !!!

如果我错了,请不要犹豫纠正我,我已经在我的 Linux 服务器上测试过了。

对不起我的英语。