我一直在try 用一个 node 设置HTTPS.我正在做的js项目.对于这个例子,我基本上遵循了node.js documentation:

// curl -k https://localhost:8000/
var https = require('https');
var fs = require('fs');

var options = {
  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};

https.createServer(options, function (req, res) {
  res.writeHead(200);
  res.end("hello world\n");
}).listen(8000);

现在,当我

curl -k https://localhost:8000/

我明白了

hello world

正如所料.但如果我这么做了

curl -k http://localhost:8000/

我明白了

curl: (52) Empty reply from server

回想起来,这似乎是显而易见的,它将以这种方式工作,但同时,最终访问我的项目的人不会键入https://yadayada,我希望从他们访问网站的那一刻起,所有流量都是https.

How can 我明白了 node (and Express as that is the framework I'm using) to hand off all incoming traffic to https, regardless of whether or not it was specified? I haven't been able to find any documentation that has addressed this. Or is it just assumed that in a production environment, node has something that sits in front of it (e.g. nginx) that handles this kind of redirection?

这是我第一次涉足网络开发,如果这是显而易见的,请原谅我的无知.

推荐答案

瑞安,谢谢你给我指出了正确的方向.我用一些代码充实了你的答案(第二段),效果不错.在这个场景中,这些代码片段被放在我的express应用程序中:

// set up plain http server
var http = express();

// set up a route to redirect http to https
http.get('*', function(req, res) {  
    res.redirect('https://' + req.headers.host + req.url);

    // Or, if you don't want to automatically detect the domain name from the request header, you can hard code it:
    // res.redirect('https://example.com' + req.url);
})

// have it listen on 8080
http.listen(8080);

https express服务器在3000上监听ATM.我设置了这些iptables规则,这样 node 就不必以root用户身份运行:

iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 443 -j REDIRECT --to-port 3000

总之,这完全符合我的要求.

要防止通过HTTP窃取Cookie,请参阅this answer(来自注释)或使用以下代码:

const session = require('cookie-session');
app.use(
  session({
    secret: "some secret",
    httpOnly: true,  // Don't let browser javascript access cookies.
    secure: true, // Only use cookies over https.
  })
);

Node.js相关问答推荐

从目录中获取所有文件,而不是NodeJS中的单个文件

如何在ejs模板中使用循环显示多个结果?

对于具有重叠列的组合键,在冲突&q;上没有唯一或排除约束匹配错误

Sass-TypeError:无法读取未定义的属性(正在读取';indexOf';)

React原生Nodejs兼容性问题

使用AWS SDK for JavaScript V3将图像从node.js上传到s3 bucket

Next.js 路由不起作用 - 页面未正确加载

找不到模块bcryptjs

BrowserRouter 无法渲染组件

如何找到特定文档并更新数组中特定键的值?

try 在 Heroku 中部署 PRN 应用程序并获得 404

用户通过 oauth2 twitter 授权或通过Passport discord后如何重定向到 React/Vue 路由?

在 NodeJS/ESP32 中通过 WebSocket 发送二进制数据 - 如何识别二进制和文本消息

JAVASCRIPT:foreach 循环后的空数组

异步函数 - 等待不等待promise

Fluxible 中的脱水和再水合代表什么?

- configuration.output.path:提供的值public不是绝对路径!使用 Webpack

NodeJS 中的 HTTPS 请求

Puppeteer 等待所有图像加载然后截图

FireStore 如果不存在则创建一个文档