• Home
  • Jobs
  • Courses
  • Questions
  • Teachers
  • For business
  • ES/EN

0

39
Views
ERR_TOO_MANY_REDIRECTS after calling res.redirect

I have below code to redirect http traffic to https but it is giving ERR_TOO_MANY_REDIRECTS

any reason ? How we can fix it in node js?

 module.exports = [
    '/',
    (req, res, next) => {
        if (req.hostname !== 'localhost' && req.protocol === 'http') {
            let url = 'https://' + req.headers.host + req.url;
            res.redirect(url);
        } else {
            next();
        }
    },
];

Note : value of req.protocol is always returning http for https requests on server.

I hit https url and checked req.protocol value and it was http

about 2 months ago ·

Juan Pablo Isaza

2 answers
Answer question

0

Can you try to debug it, to know the following:

  • Do you enter in the if statement
  • If yes, what are the values for req.protocol and req.hostname, for the first iteration, and for the next one(s), to see if these are the values you are expected for
about 2 months ago · Juan Pablo Isaza Report

0

Instead of redirecting the HTTP traffic to HTTPS by using the Nodejs code. I'd prefer you to configure the redirect directly inside your webserver Apache or Nginx and You can also use Cloudflare if you don't have Apache or Nginx access on your server. And also you are facing this problem because you are maybe redirecting visitors multiple times. For example, I think you are already redirecting traffic via webserver, and after you are again redirecting via the code. So, I'd prefer you to remove this middleware.

about 2 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.