我本地测试时, HTTP使用3000端口, HTTPS使用443.
同时监听HTTP和HTTPS
参考上一篇文章Express本地测试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}`); });
注意这里面有两个修改:
- httpApp.get 改成了 httpApp.all
- redirect时加上了第一个参数307 (TEMPORARY_REDIRECT)
只加上第一个修改的话, 重定向的时候不会保留Method, 导致POST请求变成了GET请求. 加上第二个修改就好了.
参考:
How do I redirect all unmatched urls with Express"_blank" href="https://stackoverflow.com/questions/38810114/node-js-with-express-how-to-redirect-a-post-request" rel="external nofollow" >Node.js with Express: how to redirect a POST request
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。