最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

在express.js上启用HTTPS

运维笔记admin12浏览0评论

在express.js上启用HTTPS

在express.js上启用HTTPS

我正在尝试使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);

并且当我运行此应用程序时,它does响应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流量攻击您的计算机。


回答如下:

在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)。

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论