【问题标题】:node.js https server not loading respondingnode.js https服务器没有加载响应
【发布时间】:2016-07-20 02:43:33
【问题描述】:

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

我首先按照本指南创建证书和密钥:

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.

【问题讨论】:

  • 我猜这可能与端口有关,https通常适用于443端口。你可以试试。
  • 如果没有给出端口,那么它在 443 工作。定义了端口常量。
  • 知道了 - 我尝试在 443 上运行,但仍然收到 this site can't be reached。我用更多错误详细信息更新了我的问题。
  • 关于端口,应该在 3000 上工作并不重要。当您生成密钥时,您将什么设置为 FQDN?另请提供有关您的系统的信息。
  • 嗯..我可能不是。我指定的唯一特定于我的服务器信息的通用名称是 localhost.. 您能否提供一个链接,说明如何正确将其设置为 FQDN?

标签: node.js https


【解决方案1】:

我使用express 作为网络服务器。 安装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();

【讨论】:

    【解决方案2】:

    你的代码有很多问题。

    我很快就测试了。

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

    这将引发语法错误,阻止代码继续执行,因此服务器根本无法启动。

    正如我在评论中提到的,使用 devtool 调试并在 CLI devtool server.js -w 上使用以下行,其中 -w 在开发时监视文件更改并动态重新加载服务器。 还假设您将条目文件命名为 server.js

    【讨论】:

      猜你喜欢
      • 2015-01-05
      • 2021-06-06
      • 1970-01-01
      • 2013-06-02
      • 1970-01-01
      • 1970-01-01
      • 2014-06-04
      • 2011-08-22
      • 2017-01-09
      相关资源
      最近更新 更多