Express JS如何将所有HTTP流量重定向到https(Heroku)

时间:2018-12-12 15:54:44

标签: reactjs express heroku

我想让Express JS应用程序中的一种机制将所有HTTP流量重定向到https流量,类似于Rails的force_ssl配置。 (在Rails的情况下,它只是将重定向响应发送回客户端

我认为Express服务器代码可以在Server.js中使用,但是我需要将这些请求与应该发送到实际应用程序的安全(https)请求区分开。

我认为重定向代码如下:

var http = express.createServer();
http.get('*', function(req, res) {
  res.redirect('https://' + req.headers.host + req.url);    
})
// have it listen on 8080
http.listen(80);

您会注意到,我实际上无法按端口号监听端口,因为在Heroku上增加了一个复杂的问题,即可能会重新部署该应用程序,以监听他们选择的应用程序端口(每次重新部署时都会更改)。

因此,从本质上讲,我需要一种无需使用Express设置中的端口号即可检测协议(http或https)的方法,然后将http流量重定向至https。

该应用程序本身是根据此处https://originmaster.com/running-create-react-app-and-express-crae-on-heroku-c39a39fe7851的“在Heroku上创建React应用程序”建模的,因此从本质上讲,它是由Heroku上的Express JS提供服务的REACT应用程序。

以及此处的示例应用https://github.com/Johnnycon/crae-heroku

我被困的是我检查了'process'变量,尽管它包含很多信息,但随着请求的到来,它似乎不包含任何请求信息,例如协议或url。

有任何提示或建议吗?

1 个答案:

答案 0 :(得分:2)

通常在顶部的server.js中,添加以下功能:

// On Heroku, SSL termination happens at the load balancer,
// BEFORE encrypted traffic reaches your node app.
function enforceHttps(req, res, next) {
  // Check if directly requested via https
  if (req.secure) {
    next();
    // Heroku sets a header X-Forwarded-Proto to pass the user requested protocol
  } else if ((req.headers['x-forwarded-proto'] || '').substring(0, 5) === 'https') {
    next();
    // Only redirect GET and HEAD requests
  } else if (req.method === 'GET' || req.method === 'HEAD') {
    const host = req.headers['x-forwarded-host'] || req.headers.host;
    // redirect with 301 Moved Permanently instead of default 302
    res.redirect(301, `https://${host}${req.originalUrl}`);
  } else {
    res.status(403).send('This server requires an HTTPS connection.');
  }
}

,然后在定义app(通常为const app = express();)之后进入文件:

app.use(enforceHttps);