Node.js ExpressJS 模式匹配不等于

标签 node.js express

我正在使用带有 Node 的 ExpressJS 并运行 https 和 http。

我想要求 /secure/* 的所有路由都使用 https。这样就完成了:

app.all("/secure/*", function(req, res, next) {
    if (!req.connection.encrypted) {
        res.redirect("https://" + req.headers["host"].replace(new RegExp(config.http_port, "g"), config.https_port) + req.url); 
    } else {
        return next();
    };
});

但是,我还想要求所有不使用 /secure/* 并尝试访问 https 的路由都使用相同的方法重定向到 http。

我尝试这样做:

app.all("*", function(req, res, next) {
    console.log(req);
    if (req.connection.encrypted) {
        res.redirect("http://" + req.headers["host"].replace(new RegExp(config.https_port, "g"), config.http_port) + req.url); 
    } else {
        return next();
    };
});

但是在访问 https 页面时我最终陷入了重定向循环。有没有办法指定除 /secure/* 之外的所有路由?

谢谢!

最佳答案

解决您问题的一个简单方法是:

app.all("*", function(req, res, next) {
    if (req.connection.encrypted && !/^\/secure/.test(req.url)) {
        res.redirect("http://" + req.headers["host"].replace(new RegExp(config.https_port, "g"), config.http_port) + req.url); 
    } else {
        return next();
    };
});

仅当 URL 不以 /secure 开头时才执行重定向。

但是,我建议不要在 URL 中使用多余的“安全”标签,而只需将某些路径标记为 requireHTTPrequireHTTPS。您知道您可以将多个方法传递到 app.get 和其他此类路由器方法中,对吧?假设您定义了 requireHTTPrequireHTTPS (这与您的原始函数相同),您只需执行以下操作:

app.get("/path/to/keep/encrypted", requireHTTPS, function(req, res) {
    // Rest of controller
});

app.get("/path/to/keep/public", requireHTTP, function(req, res) {
    // Rest of controller
});

app.get("/path/you/dont/care/about/encryption/status", function(req, res) {
    // Rest of controller
});

应该可以了。

关于Node.js ExpressJS 模式匹配不等于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10744351/

相关文章:

javascript - Nodemailer 包括通过数组迭代表

javascript - 我的 Firebase 网站始终只允许一名用户登录,为什么?

javascript - Node/Express 中的环境变量到底是什么?

node.js - 使用 HBS(express-handlebars)检查两个字符串

javascript - 如何使用react-router 2作为expressjs的服务器端路由?

node.js - 在 node + Mongodb + Redis 中构建一个简单的新闻提要

javascript - 在 MongoDB 查找函数中,我回调并使用 res.redirect,我收到无法设置 header 错误?

javascript - Http Request 无法在 Nodejs 服务器中立即发送响应

javascript - 了解 Passport 、序列化失败、401 错误

javascript - 类型错误 : Recaptcha is not a constructor