node.js expressjs模式匹配不相等
我将expressjs与node一起使用,并同时运行https和http 我想要求node.js expressjs模式匹配不相等,node.js,express,Node.js,Express,我将expressjs与node一起使用,并同时运行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"),
/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中使用冗余的“安全”标签,只需将某些路径标记为requireHTTP
或requireHTTPS
。您知道您可以将多种方法传递到应用程序。获取和其他类似的路由器方法,对吗?假设您定义了requireHTTP
和requireHTTPS
(与原始函数相同),您只需执行以下操作:
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
});
这样就可以了。解决问题的简单方法是:
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中使用冗余的“安全”标签,只需将某些路径标记为requireHTTP
或requireHTTPS
。您知道您可以将多种方法传递到应用程序。获取和其他类似的路由器方法,对吗?假设您定义了requireHTTP
和requireHTTPS
(与原始函数相同),您只需执行以下操作:
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
});
这应该可以做到。在第二个重定向中,您不应该只将非/secure/*
请求重定向到http://
?在第二个重定向中,您不应该只将非/secure/*
请求重定向到http://
?