javascript - express 4.x redirect http to https -


i have 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, , redirect https var httpserver = http.createserver(function(req,res){     res.redirect(config.serverdomain+req.url); }); httpserver.listen(config.httpserverport); 

but somehow can't https request redirected https request, how should correctly on node.js express 4.x ?

quoting middleware solution my own answer (which btw on express 3.0)

app.all('*', ensuresecure); // @ 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 need non defaults   // res.redirect('https://' + req.host + req.url); // express 3.x   res.redirect('https://' + req.hostname + req.url); // express 4.x } 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -