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

前端之家收集整理的这篇文章主要介绍了javascript – express 4.x将http重定向到https前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下代码
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);

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

解决方法

引用一个中间件解决方案从 my own answer(它是快速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
}
原文链接:https://www.f2er.com/js/153790.html

猜你在找的JavaScript相关文章