redirect all request http to https express js

In order to redirect all HTTP requests to HTTPS in Express.js, you can use the following code snippet:

app.use(function(req, res, next) {
  if (req.secure) {
    next();
  } else {
    res.redirect('https://' + req.headers.host + req.url);
  }
});

Explanation: 1. The app.use() function is used to mount the middleware function. 2. The middleware function takes three parameters: req (request object), res (response object), and next (callback function). 3. Inside the middleware function, an if statement checks if the request is secure (HTTPS). If it is, the next() function is called to pass control to the next middleware. 4. If the request is not secure (HTTP), the res.redirect() function is used to redirect the request to the HTTPS version of the requested URL by using the https:// protocol, req.headers.host for the host, and req.url for the requested URL.

This code ensures that all HTTP requests are automatically redirected to their HTTPS counterparts, enhancing the security of the web application.