gpt4 book ai didi

node.js - 在 Express 上伪造 req.host 值

转载 作者:太空宇宙 更新时间:2023-11-04 01:06:16 25 4
gpt4 key购买 nike

我的网络应用程序以这种方式管理用户的个人资料:

username.mywebsite.com

我使用子域表达模块来管理它,它工作得很好。 (https://www.npmjs.org/package/subdomain)

var subdomain = '/subdomain/:profileurl';
app.get(subdomain+'/user-home', main.isThisProfileExist, main.getHome);
app.get(subdomain+'/user-info', main.isThisProfileExist, main.getInfo);
app.get(subdomain+'/user-data', main.isThisProfileExist, main.getData);
...

但是,很少有用户有权将他们的个人资料与他们的自定义域名 (CNAME) 链接起来,这就是我的问题开始的地方:我找不到让我的快速路由发挥作用的方法。所以我正在考虑一种方法来伪造expressjs的req.host值。但我认为这不是最好的继续方式。

例如,用户为其域名添加了此 CNAME 记录:

customdomain.com    CNAME    username.mywebsite.com

但是在express中我会得到req.host值:

customdomain.com

这是逻辑,但它不符合我对这种情况的需要,因为我无法知道哪个配置文件是目标......

你有什么想法可以帮助我吗?

谢谢

最佳答案

如果您不希望用户必须告诉您他们的自定义 CNAME 是什么,您可以在收到的主机上自行执行 DNS 查找。

类似于:

var dns = require('dns');
var domains = dns.resolveCname(req.host);

您可以使用 connect 轻松地将其添加为您自己的中间件:

app.use(myCustomDomainLookup());

中间件模块中的实现可能如下所示:

var dns = require('dns');

module.exports = function () {
return function (req, res, next) {
if (!recognisedSubdomain(req.host)) {
var domains = dns.resolveCname(req.host);
var validProfiles = domains.map(main.ifThisProfileExists);
req._profile = validProfiles[0]; // Picking first valid profile
}
next();
}
}

编辑:

为了清楚起见,在此处添加注释中的代码。

要与您的子域中间件集成,您需要覆盖 req.host。这意味着您的中间件需要在子域中间件之前使用

您应该能够按如下方式调整上面的“if” block :

if (!recognisedSubdomain(req.host)) {
var domains = dns.resolveCname(req.host);
req.host = domains[0];
}

由于resolveCname 的文档表明可以返回一系列域,因此您必须决定在返回多个域时要执行的操作。

关于node.js - 在 Express 上伪造 req.host 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22727953/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com