在测试节点服务器上启用SSL

时间:2013-05-28 13:54:24

标签: javascript node.js ssl angularjs

我正在尝试调整node server included with the angular-seed project来提供SSL服务。基于他们所拥有的example

// HTTPS
var https = require('https');
// read in the private key and certificate
var pk = fs.readFileSync('./privatekey.pem');
var pc = fs.readFileSync('./certificate.pem');
var opts = { key: pk, cert: pc };
// create the secure server
var serv = https.createServer(opts, function(req, res) {
  console.log(req);
  res.end();
});
// listen on port 443
serv.listen(443, '0.0.0.0');

我尝试了以下操作,它似乎正在运行(没有记录错误),但是当我导航到https://localhost:8000/home时,我得到“此网页不可用”http://localhost:8000/home - 非SSL - 在我之前工作攻击了节点服务器。我怎样才能将其作为SSL工作?

#!/usr/bin/env node

var util = require('util'),
    http = require('http'),
    fs = require('fs'),
    url = require('url'),
    https = require('https'),
    events = require('events');

// read in the private key and certificate
var pk = fs.readFileSync('./scripts/privatekey.pem');
var pc = fs.readFileSync('./scripts/certificate.pem');
var opts = { key: pk, cert: pc };

var DEFAULT_PORT = 8000;

function main(argv) {  
  // create the secure server
  new HttpServer({ key: pk, cert: pc,
    'GET': createServlet(StaticServlet),
    'HEAD': createServlet(StaticServlet)
  }).start(Number(argv[2]) || DEFAULT_PORT);
}
[... balance of script omitted ...]

1 个答案:

答案 0 :(得分:0)

节点服务器代码定义

function HttpServer(handlers) {
  this.handlers = handlers;
  this.server = http.createServer(this.handleRequest_.bind(this));
}

然后继续扩展,例如:

HttpServer.prototype.start = function(port) {
  this.port = port;
  this.server.listen(port);
  util.puts('Http Server running at http://localhost:' + port + '/');
};

基于对node docs的进一步阅读,这是一个必须成为http.createServer(this.handleRequest_.bind(this))的f https.createServer(this.handleRequest_.bind(this)) - 我仍然不确定在何处/如何传递证书密钥进入过程。

鉴于一个等效的快递ssl服务器会更容易弄明白,我想我只会切换。 (以下是未经测试的。一旦我测试过,我会根据需要进行更新。)

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

// This line is from the Node.js HTTPS documentation.
var options = {
  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};

// Create a service (the app object is just a callback).
var app = express();
app.use(express.static(__dirname));

// Create an HTTP service.
// http.createServer(app).listen(80);

// Create an HTTPS service identical to the HTTP service.
https.createServer(options, app).listen(8000);
相关问题