Node.JS、Express 和 Heroku - 如何处理 HTTP 和 HTTPS?

2023-11-22

我有一个非常普通的 Express 应用程序 - 简单的服务器逻辑、视图、大量客户端 JS。 我必须执行许多 AJAX 请求。其中一些需要通过 HTTPS 协议进行保护(有些则不需要)。

因此,我的服务器应该同时支持 HTTP 和 HTTPS。 它也应该可以在本地机器(通常使用 nodemon 运行)和 Heroku 上运行。

据我了解,Heroku 为您提供了一个可以侦听的端口(process.env.PORT),并通过代理处理所有请求(因此,您的应用程序正在侦听此端口而不用担心原型 - 对吧? )

那么,我的理解是否正确——我应该为开发机和 Heroku 使用一些不同的代码?

Like

...
app = express()
...

if process.env.NODE_ENV == 'production'
  app.listen(process.env.PORT)
else
  https = require('https')
  http = require('http')
  http.createServer(app).listen(5080) # some local port
  options = {
    key: fs.readFileSync('key.pem'), 
    cert: fs.readFileSync('cert.pem') # my self-signed files
  }
  https.createServer(options, app).listen(5443) # some different local port

这是处理这个问题的正确方法吗?


对于 Coffeescript 挑战,这里是 Guard 的答案转换为 Javascript 的版本。我采用了不同的方法来拆分 if else 语句。

var express = require('express');
var http = require('http');
var https = require('https');
var fs = require('fs');
var privateKey = fs.readFileSync('./config/localhost.key').toString();
var certificate = fs.readFileSync('./config/localhost.crt').toString();

var options = {
  key : privateKey
, cert : certificate
}

var app = express();

// Start server.
var port = process.env.PORT || 3000; // Used by Heroku and http on localhost
process.env['PORT'] = process.env.PORT || 4000; // Used by https on localhost

http.createServer(app).listen(port, function () {
    console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});

// Run separate https server if on localhost
if (process.env.NODE_ENV != 'production') {
    https.createServer(options, app).listen(process.env.PORT, function () {
        console.log("Express server listening with https on port %d in %s mode", this.address().port, app.settings.env);
    });
};

if (process.env.NODE_ENV == 'production') {
    app.use(function (req, res, next) {
        res.setHeader('Strict-Transport-Security', 'max-age=8640000; includeSubDomains');
        if (req.headers['x-forwarded-proto'] && req.headers['x-forwarded-proto'] === "http") {
            return res.redirect(301, 'https://' + req.host + req.url);
        } else {
            return next();
            }
    });
} else {
    app.use(function (req, res, next) {
        res.setHeader('Strict-Transport-Security', 'max-age=8640000; includeSubDomains');
        if (!req.secure) {
            return res.redirect(301, 'https://' + req.host  + ":" + process.env.PORT + req.url);
        } else {
            return next();
            }
    });

};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Node.JS、Express 和 Heroku - 如何处理 HTTP 和 HTTPS? 的相关文章

随机推荐