如何使用Express for HTTPS的路由?

我正在对我的nodeJS服务器启用https请求。 但我想使用相同的路由,我可以从HTTP请求与8080端口接收到我的HTTPS与443端口。

http://api.myapp.com:8080/api/waitlist/join成功https://api.myapp.com:443/api/waitlist/join不是我在代码中错过了什么,以使用相同的httpsServer的“应用程序”的路线?

var fs = require('fs'); var https = require('https'); var express = require('express'); // call express var app = express(); // define our app using express var bodyParser = require('body-parser'); var mongoose = require('mongoose'); var cors = require('cors'); var config = require('./config'); // Configure app to use bodyParser() [...] // Configure the CORS rights app.use(cors()); // Enable https var privateKey = fs.readFileSync('key.pem', 'utf8'); var certificate = fs.readFileSync('cert.pem', 'utf8'); var credentials = { key: privateKey, cert: certificate }; var httpsServer = https.createServer(credentials, app); // Configure app port var port = process.env.PORT || config.app.port; // 8080 // Configure database connection [...] // ROUTES FOR OUR API // ============================================================================= // Create our router var router = express.Router(); // Middleware to use for all requests router.use(function(req, res, next) { // do logging console.log('>>>> Something is happening. Here is the path: '+req.path); next(); }); // WAITLIST ROUTES --------------------------------------- // (POST) Create Email Account --> Join the waitList router.route('/waitlist/join').post(waitlistCtrl.joinWaitlist); // And a lot of routes... // REGISTER OUR ROUTES ------------------------------- // All of our routes will be prefixed with /api app.use('/api', router); // START THE SERVER // ============================================================================= app.listen(port); httpsServer.listen(443); 

谢谢!

在我自己的需求相似的项目中使用API文档 ,并查看代码,我认为应该有两个快速的改变:

1)添加var http = require('http'); 与您的其他要求顶部。

2)将应用程序的最后两行更改为:

 // START THE SERVER // ============================================================================= http.createServer(app).listen(port); https.createServer(credentials, app).listen(443); 

(如果这个工作,你也可以删除对httpsServer的引用。)

说实话,除非你有一个非常好的理由,不要把你的networking服务器(NGINX)放在你的节点应用程序或负载平衡器前面。

这有很多方面的帮助,其中最重要的是你可以在那里终止HTTPS请求,让你的节点应用程序不在意。