Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

258
Vistas
HTTP to HTTPS redirection in Node and Angular 2 App

I have an app which runs on 80 and 443 port. When user hit http version application, it should get redirected to HTTPS. I have tried the below code to do this.

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 app started, if I hit localhost it should get redirected to https://localhost. But its not working as expected. Whats wrong in the code. I have refferred HTTPS redirection for all routes node.js/express - Security concerns

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

I would just setup https so that it only redirects in a production environment, the code I use on my site is as follows.

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 */
};
about 4 years ago · Santiago Trujillo Denunciar

0

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');
});
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda