Redirecting HTTP-HTTPS in Node and Angular 2 Applications

I have an application that runs on ports 80 and 443. When the user hits the http version of the app, they should be redirected to HTTPS. I've tried using this code below.

function handleRedirects(req, res, next) {
    if (!req.secure) {
        return res.redirect('https://' + req.get('host') + req.url);
    }
    next();
}

app.use(handleRedirects);

https.createServer(credentials, app).listen(443, function() {
    console.log('App is running on port 443');
});

// all other routes are handled by Angular
app.get('/*', function(req, res) {
    console.log("Default handler\n\n\n\n")
    res.sendFile(path.join(__dirname, '/../../dist/index.html'));
});

app.listen(80, function() {
    logger.info('App is running on port 80');
    admins.refresh();
});

      

So when the app started, if I hit localhost it should be redirected to https: // localhost . But it doesn't work as expected. What's wrong in the code. I have redirected HTTPS redirect for all node.js / express routes - security issues

+3


source to share


2 answers


Below code solved my problem.



var app = express();
app.get('/refresh', function (req, res) {
    res.send(200);
});
https.createServer(credentials, app).listen(443, function () {
  console.log('App is running on port 443');
});


var http = express();

http.get('/', function (req, res) {
  res.redirect('https://' + req.get('host') + req.url);
})
http.listen(80, function () {
  logger.info('App is running on port 80');
});

      

+1


source


I would just set up https so that it only redirects in a production environment, the code I am using on my site looks like this.



module.exports.httpsRedirect = function(req,res,next){
 if(req.headers['x-forwarded-proto'] != 'https' && process.env.NODE_ENV === 'production')
    res.redirect('https://'+req.hostname+req.url)
 else
    next() /* Continue to other routes if we're not redirecting */
};

      

+1


source







All Articles