Categories
JavaScript Answers

How to add automatic HTTPS connection or redirect with Node.js and Express?

Spread the love

Sometimes, we want to add automatic HTTPS connection or redirect with Node.js and Express.

In this article, we’ll look at how to add automatic HTTPS connection or redirect with Node.js and Express.

How to add automatic HTTPS connection or redirect with Node.js and Express?

To add automatic HTTPS connection or redirect with Node.js and Express, we can call res.redirect.

For instance, we write

const http = express();

http.get('*', (req, res) => {
  res.redirect('https://' + req.headers.host + req.url);

})

http.listen(8080);

to call res.redirect with the URL we want to redirect to.

We get the hostname with req.headers.host.

And we get the rest of the URL from req.url.

Conclusion

To add automatic HTTPS connection or redirect with Node.js and Express, we can call res.redirect.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *