English 中文(简体)
node.js Exerajs 模式匹配不等于
原标题:node.js expressjs pattern match not equal

我使用有节点的快递和运行 https 和 http 。

我要要求所有 /security/ / code> 的路线都使用 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();
    };
});

然而,我还要要求所有未使用 /security//code > 并试图访问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 页面时,我最终会陷入一个重定向循环。 除了有 < code>/ security/ / code > 的路径之外, 是否有办法指定所有路径?

谢谢!

最佳回答

解决你问题的一个简单办法是:

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 不以 < code>/ security 启动时, 才会进行重定向 。

然而,我提议,不要在 URL 中设置多余的安全标签, 只需将某些路径标记为 < code> requireHTTP 或 < code> requireHTTPS 。 您可以将多种方法传递到 < code> app.get 和其他类似的路由器方法中, 对吗? 假设您定义了 < code> requireHTTPP 和 < code> (与您原有功能完全相同), 您就会做到 :

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
});

这样应该可以了

问题回答

暂无回答




相关问题
How to make Sequelize use singular table names

I have an model called User but Sequelize looks for the table USERS whenever I am trying to save in the DB. Does anyone know how to set Sequelize to use singular table names? Thanks.

What is Node.js? [closed]

I don t fully get what Node.js is all about. Maybe it s because I am mainly a web based business application developer. What is it and what is the use of it? My understanding so far is that: The ...

Clientside going serverside with node.js

I`ve been looking for a serverside language for some time, and python got my attention somewhat. But as I already know and love javascript, I now want learn to code on the server with js and node.js. ...

Can I use jQuery with Node.js?

Is it possible to use jQuery selectors/DOM manipulation on the server-side using Node.js?

How do I escape a string for a shell command in node?

In nodejs, the only way to execute external commands is via sys.exec(cmd). I d like to call an external command and give it data via stdin. In nodejs there does yet not appear to be a way to open a ...

热门标签