我有一个简单的Express.js实例,它为单个页面Angular应用程序提供静态资产。我在Express配置中设置了一些中间件,以便为所有路由返回index.html,并且可以从那里加载Angular。Express.js重定向到HTTPS并发送index.html
最近,我在Heroku上设置了SSL,我想确保所有来自HTTP的流量都被重定向到HTTPS。我试图将来自this post的建议解决方案与我现在拥有的解决方案结合起来,但最终会陷入无尽的重定向循环。
简而言之,我需要将所有流量从HTTP重定向到HTTPS,并为所有请求发送index.html文件。我在这里做错了什么?
var gzippo = require('gzippo');
var express = require('express');
var morgan = require('morgan');
var app = express();
// set environment variables
var env = app.get('env') || 'development';
app.use(morgan('dev'));
// serve static assets
app.use(gzippo.staticGzip("" + __dirname + "/dist"));
app.use("/js", express.static(__dirname + "/dist/scripts"));
app.use("/fonts", express.static(__dirname + "/fonts"));
app.use("/img", express.static(__dirname + "/dist/assets/images"));
app.use("/css", express.static(__dirname + "/dist/styles"));
// Redirect all HTTP traffic to HTTPS
function ensureSecure(req, res, next){
if(req.secure){
// OK, continue
return next();
};
res.redirect('https://'+req.hostname+req.url); // handle port numbers if you need non defaults
};
// Always send index.html
function sendIndex(req, res, next) {
res.sendfile('index.html', { root: __dirname + "/dist/"});
}
// Handle environments
if (env == 'production') {
app.all('*', ensureSecure);
}
app.all('/*', sendIndex);
// Start server
app.listen(process.env.PORT || 5000);
太棒了,这似乎为我工作。我在这里唯一的另一个问题是,它不会在根上应用重定向,只能在其他路由上应用。我试着把'''app.all'''改成'''app.use(ensureSecure);'''没有运气。有关于此的任何想法? –
@WillHitchcock是的,我打算建议使用app.use而不是app.all,但不确定如果这不起作用,问题是什么。尝试添加更多的日志来跟踪在这种情况下发生的情况。 – Philippe
我想我明白了。我只需要在'''app.use(gzippo ...'''line'之前加入重定向。立即工作! –