我本地測(cè)試時(shí), HTTP使用3000端口, HTTPS使用443.
同時(shí)監(jiān)聽HTTP和HTTPS
參考上一篇文章Express本地測(cè)試HTTPS
轉(zhuǎn)發(fā)所有GET請(qǐng)求
httpApp.get("*", (req, res, next) => {
let host = req.headers.host;
host = host.replace(/\:\d+$/, ''); // Remove port number
res.redirect(`https://${host}${req.path}`);
});
相當(dāng)于自己拼接上https的鏈接然后redirect. 此時(shí)瀏覽器會(huì)收到302 (MOVED_TEMPORARILY)狀態(tài)碼, 并重定向到HTTPS.
轉(zhuǎn)發(fā)所有請(qǐng)求
httpApp.all("*", (req, res, next) => {
let host = req.headers.host;
host = host.replace(/\:\d+$/, ''); // Remove port number
res.redirect(307, `https://${host}${req.path}`);
});
注意這里面有兩個(gè)修改:
-
httpApp.get
改成了httpApp.all
-
redirect
時(shí)加上了第一個(gè)參數(shù)307
(TEMPORARY_REDIRECT)
只加上第一個(gè)修改的話, 重定向的時(shí)候不會(huì)保留Method, 導(dǎo)致POST
請(qǐng)求變成了GET
請(qǐng)求. 加上第二個(gè)修改就好了.
參考: