javascript express 4.x 将 http 重定向到 https

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24015292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:59:13  来源:igfitidea点击:

express 4.x redirect http to https

javascriptnode.jshttpredirectexpress

提问by uray

i have the following code :

我有以下代码:

var https        = require('https');
var http         = require('http');
var express      = require('express');
var app          = express();
var router       = express.Router();

app.use('/', router);

//listen server on https
var server = https.createServer(config.sslCredential, app);
server.listen(config.serverPort);

//listen server on http, and always redirect to https
var httpServer = http.createServer(function(req,res){
    res.redirect(config.serverDomain+req.url);
});
httpServer.listen(config.httpServerPort);

but somehow i can't get https request to be redirected into https request, how should i do this correctly on node.js with express 4.x ?

但不知何故,我无法将 https 请求重定向到 https 请求,我应该如何在带有 express 4.x 的 node.js 上正确执行此操作?

回答by Plato

Quoting a middleware solution from my own answer(which btw was on express 3.0)

我自己的答案中引用一个中间件解决方案(顺便说一句,在 express 3.0 上)

app.all('*', ensureSecure); // at top of routing calls

http.createServer(app).listen(80)
https.createServer(sslOptions, app).listen(443)

function ensureSecure(req, res, next){
  if(req.secure){
    // OK, continue
    return next();
  };
  // handle port numbers if you need non defaults
  // res.redirect('https://' + req.host + req.url); // express 3.x
  res.redirect('https://' + req.hostname + req.url); // express 4.x
}