Node.JS,Express和Heroku – 如何处理HTTP和HTTPS?

我有一个应用程序是非常正常的快速应用程序 – 简单的服务器逻辑,视图,大量的客户端JS。 我必须做很多的AJAX请求。 其中一些需要通过HTTPS协议来保护(有些不需要)。

所以,我的服务器应该同时使用HTTP和HTTPS。 它也应该在本地机器(通常用nodemon运行)和Heroku上工作。

据我所知,Heroku给你一个单一的端口(process.env.PORT),你可以听,并通过代理处理所有请求(所以,你的应用程序正在听这个端口,而不是打扰原始的权利? )

所以,我得到这个权利 – 我应该有一些不同的开发机器和Heroku的代码?

喜欢

... app = express() ... if process.env.NODE_ENV == 'production' app.listen(process.env.PORT) else https = require('https') http = require('http') http.createServer(app).listen(5080) # some local port options = { key: fs.readFileSync('key.pem'), cert: fs.readFileSync('cert.pem') # my self-signed files } https.createServer(options, app).listen(5443) # some different local port 

这是处理这个问题的正确方法吗?

对于Coffeescript挑战,这里是Guard的答案转换为Javascript的一个版本。 我采取了不同的方法来分裂if else语句。

 var express = require('express'); var http = require('http'); var https = require('https'); var fs = require('fs'); var privateKey = fs.readFileSync('./config/localhost.key').toString(); var certificate = fs.readFileSync('./config/localhost.crt').toString(); var options = { key : privateKey , cert : certificate } var app = express(); // Start server. var port = process.env.PORT || 3000; // Used by Heroku and http on localhost process.env['PORT'] = process.env.PORT || 4000; // Used by https on localhost http.createServer(app).listen(port, function () { console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env); }); // Run separate https server if on localhost if (process.env.NODE_ENV != 'production') { https.createServer(options, app).listen(process.env.PORT, function () { console.log("Express server listening with https on port %d in %s mode", this.address().port, app.settings.env); }); }; if (process.env.NODE_ENV == 'production') { app.use(function (req, res, next) { res.setHeader('Strict-Transport-Security', 'max-age=8640000; includeSubDomains'); if (req.headers['x-forwarded-proto'] && req.headers['x-forwarded-proto'] === "http") { return res.redirect(301, 'https://' + req.host + req.url); } else { return next(); } }); } else { app.use(function (req, res, next) { res.setHeader('Strict-Transport-Security', 'max-age=8640000; includeSubDomains'); if (!req.secure) { return res.redirect(301, 'https://' + req.host + ":" + process.env.PORT + req.url); } else { return next(); } }); }; 

那么社区现在看起来挺死的(希望我错了)

答案是:

a)是的,这是处理这个问题的方法

b)检查您是否处于安全模式的方法取决于环境:

 if process.env.NODE_ENV == 'production' is_secure = (req) -> req.headers['x-forwarded-proto'] == 'https' else is_secure = (req) -> req.secure 

添加如果你想强制HTTPS:

 redirect_to_https = (req, res, next) -> if not is_secure(req) res.redirect config.SECURE_DOMAIN + req.url else next() app .use(redirect_to_https) 

您可以使用app.enable('trust proxy') ,然后req.secure boolean(http / https)也可以在Heroku上使用,也可以在任何兼容的SSL终止代理之后使用。