Sudhanshu Gaur
Sudhanshu Gaur

Reputation: 7664

Nodejs res.redirect not working?

I have my Angularjs website and I am trying to route all my Http traffic to Https and for that, I have written below code but it is not working, every time I am opening my website on Http redirect is not happening.

var express = require('express');
var app = express();

app.use(express.static(__dirname + '/public')); // Website part added
var bodyParser = require('body-parser')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }))

app.use(function(req,res,next) {

    if(req.headers["x-forwarded-proto"] == "http") {

        res.redirect("https://" + req.headers.host + req.url);
        return next();
    } else {
        console.log('Request was not HTTP');
        return next();
    } 
});

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.get('*', function(req, res) {
    res.sendFile(__dirname + '/public/index.html');
});

Can anyone please tell me why this is not working ??

Edit - I noticed that whenever I am opening my website then most of the times this middleware is not getting called. How can this be possible ??

Edit - I have my set base href="/" in my index.html will it cause any problem.

Upvotes: 2

Views: 5732

Answers (2)

Sudhanshu Gaur
Sudhanshu Gaur

Reputation: 7664

Hello actually the mistake I was doing was I was putting redirecting on the middleware after the setting the /public directory, but the right way was to put it before setting /public directory.

Right Code

app.use(function(req,res,next) {

    if(req.headers["x-forwarded-proto"] == "http") {

        res.redirect("https://" + req.headers.host + req.url);
        return next();
    } else {
        console.log('Request was not HTTP');
        return next();
    }
});
app.use(express.static(__dirname + '/public')); // Website part added
var bodyParser = require('body-parser')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }))

Because of which Https was not enforcing but now everything is working as expected.

Upvotes: 2

TGrif
TGrif

Reputation: 5931

This is because you can't rely on x-forwarded-proto header in all case.

x-forwarded-proto is generally set when you run your app behind a proxy, and apparently it's not your case.

It would be better to use req.protocol instead:

if (req.protocol === "http") {
  res.redirect("https://" + req.headers.host + req.url);
} else {
  console.log('Request was not HTTP');
  return next();
}

Or you can use the handy Express request property req.secure.

Upvotes: 0

Related Questions