Gua*_*ard 8 heroku node.js express
我有一个非常正常的应用程序应用程序 - 简单的服务器逻辑,视图,许多客户端JS.我必须做很多AJAX请求.其中一些需要通过HTTPS协议进行保护(有些不需要).
所以,我的服务器应该同时使用HTTP和HTTPS.它也适用于本地机器(通常使用nodemon运行)和Heroku.
据我所知,Heroku为您提供了一个可以监听的单一端口(process.env.PORT),并通过代理处理所有请求(因此,您的应用程序正在侦听此端口,而不是打扰原型 - 对吗? )
那么,我是否正确 - 我应该为dev机器和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
Run Code Online (Sandbox Code Playgroud)
这是处理这个问题的正确方法吗?
Dan*_*ohn 12
对于Coffeescript-challenge,这里是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();
}
});
};
Run Code Online (Sandbox Code Playgroud)
好吧,这些天社区看起来很死(希望我错了)
答案是:
a)是的,这是处理它的方法
b)检查您是否处于安全模式的方式也取决于环境:
if process.env.NODE_ENV == 'production'
is_secure = (req) ->
req.headers['x-forwarded-proto'] == 'https'
else
is_secure = (req) -> req.secure
Run Code Online (Sandbox Code Playgroud)
ADD 如果您想强制使用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)
Run Code Online (Sandbox Code Playgroud)