0

我正在尝试调整angular-seed 项目中包含的节点服务器以服务 SSL。基于这个例子,他们有:

// 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 ...]
4

1 回答 1

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 + '/');
};

基于对节点文档的进一步阅读,它是这个片段:http.createServer(this.handleRequest_.bind(this))这将不得不成为https.createServer(this.handleRequest_.bind(this))- 我仍然不确定在哪里/如何将证书密钥传递到进程中。

鉴于等效的 express 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);
于 2013-05-28T19:28:50.843 回答