如何使用 Express 侦听端口 443?

Sha*_*oon 2 https node.js express

var app, certificate, credentials, express, fs, http, httpServer, https, httpsServer, privateKey;

fs = require('fs');

http = require('http');

https = require('https');

privateKey = fs.readFileSync('key.pem', 'utf8');

console.log(privateKey);

certificate = fs.readFileSync('cert.pem', 'utf8');

console.log(certificate);

credentials = {
  key: privateKey,
  cert: certificate
};

express = require('express');

app = express();

httpServer = http.createServer(app);

httpsServer = https.createServer(credentials, app);

httpServer.listen(80);

httpsServer.listen(443);
Run Code Online (Sandbox Code Playgroud)

我在 OS X 上,我确认没有其他东西在 80 和 443 上收听。我在运行sudo时运行http://127.0.0.1它,它可以工作。但是,当我去时https://127.0.0.1,我没有找到。

我做错了什么?

cmd*_*cmd 5

要使您的应用程序分别侦听httphttps端口80443,请执行以下操作

创建一个快速应用:

var express = require('express');
var app = express();
Run Code Online (Sandbox Code Playgroud)

返回的应用程序express()是一个 JavaScript 函数。它可以作为回调传递给 Node 的 HTTP 服务器来处理请求。这使得使用相同的代码库轻松提供应用程序的 HTTP 和 HTTPS 版本。

你可以这样做:

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

var options = {
  key: fs.readFileSync('/path/to/key.pem'),
  cert: fs.readFileSync('/path/to/cert.pem')
};

http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
Run Code Online (Sandbox Code Playgroud)

有关完整的详细信息,请参阅文档


小智 1

添加以下代码行:

app.listen(443);
Run Code Online (Sandbox Code Playgroud)

另外,尝试删除所有 http 模块,因为express 会为您处理大部分内容。查看 Express 的开头 Hello World,http://expressjs.com/starter/hello-world.html并查找它处理端口的部分。