Express SSL重定向不适用于root/



我在Express路由声明的末尾使用通配符匹配来测试连接是否不是HTTPS,如果不是,则重定向到URI的HTTPS版本。

这适用于除root以外的所有内容,即www.domain.com。这有点问题,因为domain.com提供SPA。

app.get('*', function (req, res) {
        if (req.headers['X-forwarded-proto'] != 'https') {
            res.redirect('https://domain.com/#' + url_path);
        }
        else {
            res.redirect('/#' + url_path);
        }
});

我注意到,当URL是根域时,这段代码甚至不会被调用。我想这可能是因为我还声明:

app.use(express.static(path.join(application_root, 'public')));

这对于SPA为所有资产提供服务是必要的。当我删除这一行时,我的路由处理程序现在被调用到根域,但我的主页现在无限重定向。

我必须创建一个自定义路由来服务器我的SPA文件,重命名index.html,这样Express就不会试图为它而不是我的路由提供服务。

对于那些可能仍在努力解决这个问题的人来说,我在Heroku上部署React Express应用程序时遇到了同样的问题。我使用了一个中间件:;heroku ssl重定向";。对我来说,解决方案是将这个中间件放在层次结构中(现在它是我应用的第一个中间件):

var sslRedirect = require("heroku-ssl-redirect");
const express = require('express');
const path = require('path');
const e = require('express');
const app = express();
app.use(sslRedirect());
// Serve the static files from the React app
app.use(express.static(path.join(__dirname, 'client/build')));
// Handles any requests that don't match the ones above
app.get('*', (req, res) =>{
    res.sendFile(path.join(__dirname+'/client/build/index.html'));
});
const port = process.env.PORT || 5000;
app.listen(port);
console.log('App is listening on port ' + port);

最新更新