This time I will show you how to direct HTTP to HTTPS in Express and what are the precautions. The following is a practical case, let's take a look.
When I tested locally, HTTP used port 3000 and HTTPS used port 443.
Monitoring HTTP and HTTPS at the same time
Refer to the previous article Express local test HTTPS
Forward all GET requests
httpApp.get("*", (req, res, next) => { let host = req.headers.host; host = host.replace(/\:\d+$/, ''); // Remove port number res.redirect(`https://${host}${req.path}`); });
It is equivalent to splicing the https link yourself and then redirecting. At this time, the browser will receive the 302 (MOVED_TEMPORARILY) status code and redirect to HTTPS.
Forward all requests
httpApp.all("*", (req, res, next) => { let host = req.headers.host; host = host.replace(/\:\d+$/, ''); // Remove port number res.redirect(307, `https://${host}${req.path}`); });
Note that there are two modifications:
httpApp.get is changed to httpApp.all
The first parameter 307 (TEMPORARY_REDIRECT) is added when redirecting
If only the first modification is added, when redirecting The Method will not be retained, causing the POST request to become a GET request. Just add the second modification.
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other php Chinese websites. related articles!
Recommended reading:
How to use Angularjs custom instructions in projects
How to operate JQuery elements
The above is the detailed content of How to direct HTTP to HTTPS in Express. For more information, please follow other related articles on the PHP Chinese website!