Home > Web Front-end > JS Tutorial > How to direct HTTP to HTTPS in Express

How to direct HTTP to HTTPS in Express

php中世界最好的语言
Release: 2018-06-07 09:41:05
Original
2142 people have browsed it

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}`);
});
Copy after login

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}`);
});
Copy after login

Note that there are two modifications:

  1. httpApp.get is changed to httpApp.all

  2. 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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template