gpt4 book ai didi

javascript - 在测试 Node 服务器上启用 SSL

转载 作者:太空宇宙 更新时间:2023-11-03 15:03:30 25 4
gpt4 key购买 nike

我正在尝试调整 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 - 在我破解 Node 服务器之前工作。我怎样才能让它作为 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 ...]

最佳答案

Node 服务器代码定义

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)) 必须变成 https.createServer(this.handleRequest_.bind(this)) - - 我仍然不确定在哪里/如何将证书 key 传递到流程中。

考虑到等效的 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);

关于javascript - 在测试 Node 服务器上启用 SSL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16793922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com