如何使用来自Express的HTTPS路由



我启用https请求到我的nodeJS服务器。但是我想使用相同的路由,我可以从8080端口的http请求接收到443端口的https。

http://api.myapp.com:8080/api/waitlist/join成功https://api.myapp.com: 443/api/候补名单/加入不是我在代码中错过了什么,以使用与httpserver的"app"相同的路由?

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

谢谢!

在我自己有类似需求的项目上使用.listen的API文档,并查看您的代码,我认为两个快速更改应该起作用:

1)将var http = require('http');与其他要求一起添加到顶部。

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

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

(如果这有效,您也可以删除对httpsServer的引用)

说实话,除非你有很好的理由不这样做,否则我会考虑在你的节点应用程序或负载均衡器前面放一个web服务器(NGINX)。

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

最新更新