我在Express路由声明的末尾使用通配符匹配来测试连接是否不是HTTPS,如果不是,则重定向到URI的HTTPS版本。
这适用于除根之外的所有东西,即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为所有资产服务所必需的。当我移除这一行时,我的路由处理程序现在被调用为根域,但是我的主页现在被无限重定向。
发布于 2015-04-10 15:42:24
我必须创建一个自定义路由来服务器我的SPA文件,重命名index.html,这样Express就不会尝试提供它而不是我的路由。
发布于 2020-06-20 15:07:25
对于那些仍在努力解决这个问题的人来说,我在Heroku上部署我的React应用程序时也遇到了同样的问题。我使用了一个中间件:“heroku重定向”。对我来说,解决方案是将这个中间件放到层次结构中(现在它是我应用的第一个中间件):
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);
https://stackoverflow.com/questions/29540390
复制相似问题