Node.js multiple subdomains

China☆狼群 提交于 2021-02-10 12:06:58

问题


I am using node.js to build a multi-tenant application where different clients with their own subdomains will be accessing a single instance of my app. My questions is:

Is there a way for the app to find out which subdomain a user is on? That way, I can route the user to the correct database schema (postgresql).

Thanks in advance!

Additional information:

  • I am using the Express framework
  • I'm not using multiple instances because I expect to have upwards of thousands of users and I don't want to manage thousands of instances.
  • Regarding subdomains, I mean something like:

myapp.client1domain.com

myapp.client2domain.com

myapp.client3domain.com

Each of the above url's link to the same instance of the app. However, I need to know which subdomain a user is on so I can route them to the right database schema.


回答1:


Since "host" from HTTP/1.1 or greater is reflected in the request object as "host" header. You could do something like:

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

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

Please note that port might be undefined; and do additional checks, add error handling if there is no host header or HTTP version is below 1.1. Of course you could do similar as an express middleware, or with any similar framework, this is just bare node.js http.

Update:

In express I'd do something like:

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") gives you back the host the request was directed to, e.g. myapp.client1domain.com or so (match specific part with regexp) and based on that you could set a property on res.locals which you could use on subsequent routes, or bail out in case of an unknown domain.

The above snipped would log "a connection to scheme by host: localhost", if you do a request to http://localhost:<port>/db.



来源:https://stackoverflow.com/questions/35344588/node-js-multiple-subdomains

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!