美文网首页让前端飞后端应用技术
Express的HTTP重定向到HTTPS

Express的HTTP重定向到HTTPS

作者: 柳正来 | 来源:发表于2018-06-03 03:30 被阅读23次

    我本地测试时, 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}`);
    });
    

    注意这里面有两个修改:

    1. httpApp.get 改成了 httpApp.all
    2. redirect时加上了第一个参数307 (TEMPORARY_REDIRECT)
      只加上第一个修改的话, 重定向的时候不会保留Method, 导致POST请求变成了GET请求. 加上第二个修改就好了.

    参考:

    1. How do I redirect all unmatched urls with Express?
    2. Node.js with Express: how to redirect a POST request

    相关文章

      网友评论

        本文标题:Express的HTTP重定向到HTTPS

        本文链接:https://www.haomeiwen.com/subject/icidsftx.html