我本地测试时, HTTP使用3000端口, HTTPS使用443.
同时监听HTTP和HTTPS
转发所有GET请求
httpApp.get("*", (req, res, next) => { let host = req.headers.host; host = host.replace(/:d+$/, ''); // Remove port number res.redirect(`https://${host}${req.path}`); });
相当于自己拼接上https的链接然后redirect. 此时浏览器会收到302 (MOVED_TEMPORARILY)状态码, 并重定向到HTTPS.
转发所有请求
httpApp.all("*", (req, res, next) => { let host = req.headers.host; host = host.replace(/:d+$/, ''); // Remove port number res.redirect(307, `https://${host}${req.path}`); });
注意这里面有两个修改:
只加上第一个修改的话, 重定向的时候不会保留Method, 导致POST请求变成了GET请求. 加上第二个修改就好了.
参考:
How do I redirect all unmatched urls with Express?
Node.js with Express: how to redirect a POST request