【发布时间】:2018-07-30 11:16:29
【问题描述】:
我在 Heroku 上有一个使用 create-react-app 创建的应用程序。就在今天,我使用 Heroku 的自动 (-ish) SSL 证书流程 ExpeditedSSL 获得了 SSL 证书,然后文档建议将所有 http 请求重新路由到 https。
我有一个 server.js 文件,我使用 express 来尝试运行中间件,然后为我的 React 应用程序提供服务。
我知道 SSL 证书正在工作,就好像我转到 https://myapp.com 我看到了我的 Heroku 应用程序,但是当我转到 http://myapp.com 时,它并没有重定向到我的 Heroku 应用程序的 https 版本。
我今天从 StackOverflow、Google 和其他地方尝试了很多很多 solutions,但没有一个解决方案对我有用。我也没有收到任何错误。它只是不起作用。
尝试使用https library:
const https = require("https");
const express = require('express');
const app = express();
app.use(express.static(path.join(__dirname, 'build')));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
https.createServer(app).listen(3000);
再次尝试使用heroku-ssl-redirect:
var sslRedirect = require('heroku-ssl-redirect');
var express = require('express');
var app = express();
// enable ssl redirect
app.use(sslRedirect(['production'], 301));
app.use(express.static(path.join(__dirname, 'build')));
app.get('*', (req, res, next) => {
if (req.headers['x-forwarded-proto'] != 'https'){
res.redirect('https://' + req.hostname + req.url);
} else {
next();
}
});
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.listen(process.env.PORT || 3000);
尝试使用x-forward-proto:
const express = require('express');
const env = process.env.NODE_ENV || 'development';
const bodyParser = require('body-parser');
const path = require('path');
const app = express();
var forceSsl = function (req, res, next) {
if (req.headers['x-forwarded-proto'] !== 'https') {
return res.redirect(['https://', req.get('Host'), req.url].join(''));
}
return next();
};
if (env === 'production') {
app.use(forceSsl);
}
app.use(express.static(path.join(__dirname, 'build')));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.listen(process.env.PORT || 8080);
我还尝试了一些来自各种博客和 SO 帖子的随机节点安装,但没有任何效果。如果没有任何错误,我很难弄清楚为什么这不起作用。
【问题讨论】:
-
@pritesh 是的。这是我尝试过的事情之一。不过,感谢您的回复!
标签: reactjs express ssl heroku