简体   繁体   English

如何使用Express在端口443上侦听?

[英]How do I listen on port 443 using 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);

I am on OS X and I have confirmed nothing else is listening on 80 and 443. I run this as sudo and when I go http://127.0.0.1 , it works. 我在OS X上,并且我确认没有其他声音在监听80和443。我以sudo身份运行它,当我进入http://127.0.0.1 ,它可以工作。 However, when I go to https://127.0.0.1 , I get not found. 但是,当我转到https://127.0.0.1 ,找不到。

What am I doing incorrect? 我做错了什么?

add the following line of code: 添加以下代码行:

app.listen(443);

Also, try getting rid of all of the http module, as express handles most of that for you. 另外,请尝试摆脱所有的http模块,因为express可以为您解决大部分问题。 Look at the beginning Hello World for Express, http://expressjs.com/starter/hello-world.html and look for the part where it handles the port. 查看开始的Express版Hello World, 网址http://expressjs.com/starter/hello-world.html,然后查找它处理端口的部分。

To enable your app to listen for both http and https on ports 80 and 443 respectively, do the following 若要使您的应用程序分别侦听端口80443上的httphttps ,请执行以下操作

Create an express app: 创建一个快速应用程序:

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

The app returned by express() is a JavaScript function. express()返回的应用程序是一个JavaScript函数。 It can be be passed to Node's HTTP servers as a callback to handle requests. 可以将其作为处理请求的回调传递给Node的HTTP服务器。 This makes it easy to provide both HTTP and HTTPS versions of your app using the same code base. 这使得使用相同的代码库轻松提供应用程序的HTTP和HTTPS版本。

You can do so as follows: 您可以按照以下方式进行操作:

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);

For complete detail see the doc 有关完整的详细信息,请参阅文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM