node.js https服务器不加载响应

我正在尝试启动一个https node.js服务器。

我开始按照本指南创build证书和密钥:

http://gaboesquivel.com/blog/2014/nodejs-https-and-ssl-certificate-for-development/

我把它们放在我的/app_name/security/keys目录下。

要启动我的https服务器,我有以下几点:

 const https = require('https'), fs = require('fs'); if(app.get('env') === 'development') { console.log('dev env!!'); //prints correctly console.log('port: ' + port); //prints correctly const options = { key: fs.readFileSync('./security/keys/key.pem'), cert: fs.readFileSync('./security/keys/cert.pem') }; https.createServer(options, (req, res) => { console.log('https good to go'); //this does not print out anything }).listen(port); } 

当我转到https://localhost:3000 ,页面会引发错误

 This site can't be reached localhost unexpectedly closed the connection. ERR_CONNECTION_CLOSED 

但在服务器端控制台上没有错误。 此外,如果我去正常的localhost:3000 ,我得到:

 The localhost page isn't working localhost didn't send any data. ERR_EMPTY_RESPONSE 

有人可以帮忙吗?

提前致谢!

—-更新—-

我现在在443端口上运行。 最初我得到一个错误:

Error: listen EACCES 0.0.0.0:443所以我跑:

sudo NODE_ENV=development nodemon app

哪个没有抛出任何错误。 但是,当我去到https://localhost:443 ,我得到:

 This site can't be reached localhost unexpectedly closed the connection. 

我用express作为networking服务器。 安装express

 npm install express --save 

我把你的代码,使用express ,使用openssl生成的证书,并执行它 – 一切看起来不错,服务器启动,通过https监听3000端口。

我的代码(这是基于你的代码…):

 var app = require('express')(); const https = require('https'), fs = require('fs'), port = 3000; if(app.get('env') === 'development') { console.log('dev env!!'); //prints correctly console.log('port: ' + port); //prints correctly const options = { key: fs.readFileSync('/tmp/private.key'), cert: fs.readFileSync('/tmp/publickey.crt') }; https.createServer(options, (req, res) => { console.log('https good to go'); //this does message appears!!! ^_^ }).listen(port); } 

请注意我定义app的方式: var app = require('express')();

如果可读性更好,可以将这个定义分成两行:

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

你的代码有很多问题。

我testing了这个很快。

关键字appport没有定义,分别是第4行和第7行。

这会引起你一个语法错误,阻止代码继续进行,因此服务器根本不能启动。

正如我在我的评论中提到的那样,使用devtool在CLI上debugging和使用以下行devtool server.js -w其中-w devtool server.js -w文件更改并在开发过程中dynamic地重新加载服务器。 还假设你命名你的入口文件server.js