小编典典

在express.js上启用HTTPS

node.js

我正在尝试让HTTPS在node.express.js上工作,但我无法弄清楚。

这是我的app.js代码。

var express = require('express');
var fs = require('fs');

var privateKey = fs.readFileSync('sslcert/server.key');
var certificate = fs.readFileSync('sslcert/server.crt');

var credentials = {key: privateKey, cert: certificate};


var app = express.createServer(credentials);

app.get('/', function(req,res) {
    res.send('hello');
});

app.listen(8000);

当我运行它时,它似乎仅响应HTTP请求。

我写了简单的node.js基于香草的HTTPS应用程序:

var   fs = require("fs"),
      http = require("https");

var privateKey = fs.readFileSync('sslcert/server.key').toString();
var certificate = fs.readFileSync('sslcert/server.crt').toString();

var credentials = {key: privateKey, cert: certificate};

var server = http.createServer(credentials,function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
});

server.listen(8000);

当我运行此应用程序时,它 确实 响应HTTPS请求。请注意,我认为fs结果上的toString()并不重要,因为我使用了两者的组合,但仍然没有es
bueno。


编辑添加:

对于生产系统,最好使用Nginx或HAProxy将请求代理到您的nodejs应用。您可以设置nginx来处理ssl请求,而只对您的节点app.js说HTTP。

编辑添加(4/6/2015)

对于使用AWS的系统,最好使用EC2弹性负载均衡器来处理SSL终止,并允许向EC2
Web服务器的常规HTTP通信。为了进一步提高安全性,请设置安全组,以便仅允许ELB将HTTP流量发送到EC2实例,这将防止外部未加密的HTTP流量攻击您的计算机。



阅读 389

收藏
2020-07-07

共1个答案

小编典典

在express.js(版本3起)中,应使用以下语法:

var fs = require('fs');
var http = require('http');
var https = require('https');
var privateKey  = fs.readFileSync('sslcert/server.key', 'utf8');
var certificate = fs.readFileSync('sslcert/server.crt', 'utf8');

var credentials = {key: privateKey, cert: certificate};
var express = require('express');
var app = express();

// your express configuration here

var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);

httpServer.listen(8080);
httpsServer.listen(8443);

这样,您就可以向本地http / https服务器提供快速中间件

如果您希望您的应用程序在1024以下的端口上运行,则需要使用sudo命令(不推荐)或使用反向代理(例如nginx,haproxy)。

2020-07-07