提问者:小点点

node.js多个子域


我正在使用Node.js构建一个多租户应用程序,在这个应用程序中,具有自己子域的不同客户机将访问我的应用程序的一个实例。我的问题是:

有没有一种方法可以让应用程序发现用户在哪个子域上?这样,我就可以将用户路由到正确的数据库模式(postgresql)。

提前道谢!

其他信息:

  • 我正在使用Express框架
  • 我不使用多个实例,因为我希望有数千个以上的用户,而且我不想管理数千个实例。
  • 关于子域,我的意思是:

myapp.client1domain.com

myapp.client2domain.com

myapp.client3domain.com

上面的每个URL都指向应用程序的同一实例。但是,我需要知道用户在哪个子域上,以便将他们路由到正确的数据库模式。


共1个答案

匿名用户

因为HTTP/1.1或更高版本中的“host”作为“host”头反映在请求对象中。您可以执行以下操作:

const setupDatabaseScheme = (host, port) => {
  // ...
};

http.createServer((req, res) => {
    if (req.headers.host) {
        const parts = req.headers.host.split(":");
        setupDataBaseSchema(parts[0], parts[1]);
    }
});

请注意,端口可能未定义;并进行其他检查,如果没有主机头或HTTP版本低于1.1,则添加错误处理。当然,您也可以作为一个express中间件来做类似的工作,或者使用任何类似的框架,这只是一个裸的node.js http。

更新:

在express中,我会做如下操作:

const getConnecitonForSchemeByHost = (host) => {
    // ... get specific connection for given scheme from pool or similar
    return "a connection to scheme by host: " + host;
};

router
    .all("*", function (req, res, next) {
        const domain = req.get("host").split(":")[0];
        const conn = res.locals.dbConnection = getConnecitonForSchemeByHost(domain);
        if (conn) {
            next();
        } else {
            next(new Error("no connection for domain: " + domain))
        }
    })
    .get("/", function (req, res) { // use connection from res.locals at further routes
        console.log(res.locals.dbConnection);
        res.send("ok");
    });

app.use("/db", router);

req.get(“host”)返回请求所指向的主机,例如myapp.client1domain.com左右(将特定部分与regexp匹配),并在此基础上设置res.locals上的属性,您可以在后续路由上使用该属性,或者在未知域的情况下退出。

如果您对http://localhost:/db执行请求,上述片段将记录“通过主机:localhost连接到scheme”。