2

I have node app running on express. I'd like to set up two different account types (one for buyers, one for sellers) and have them accessible through different subdomains (ie buyers.example.com and sellers.example.com). I'm not sure how to set this up locally. I know that I can edit the hosts file on my machine to have *.localhost resolve to 127.0.0.1, but that doesn't solve my problem. In that case, buyers.localhost/login and sellers.localhost/login will route to the same place. Is this a common issue, and if so, what is the standard way of handling this? What are some options for me to separate the logic for handling two account types?

jordan
  • 9,570
  • 9
  • 43
  • 78
  • Take a look at [`expressjs/vhost`](https://github.com/expressjs/vhost) ([formerly](https://github.com/senchalabs/connect#middleware) `express.vhost()` and `connect.vhost()`). Also related: "[Single node.js http server accepting connections on multiple hostnames](http://stackoverflow.com/q/5262127)," "[How do I host multiple Node.js sites on the same IP/server with different domains?](http://stackoverflow.com/q/19254583)," "[How to mount express.js sub-apps?](http://stackoverflow.com/q/8514106)," and "[Sub domains in nodejs](http://stackoverflow.com/q/13208145)" – Jonathan Lonowski Oct 16 '14 at 16:40

2 Answers2

4

First add this:

app.get('*', function(req, res, next){
    if (req.headers.host == 'buyers.localhost:5000') { //Port is important if the url has it
        req.url = '/buyers' + req.url;
    }
    else if(req.headers.host == 'sellers.localhost:5000') {
        req.url = '/sellers' + req.url;
    }  
    next();
});

And then:

app.get('/login', function(){
  //Default case, no subdomain
})

app.get('/buyers/login', function(){
   //Buyers subdomain
})

app.get('/sellers/login', function(){
   //Sellers subdomain
})

Learned this here: https://groups.google.com/forum/#!topic/express-js/sEu66n8Oju0

andresgottlieb
  • 920
  • 10
  • 18
0
app.all("*", function (req: Request, res: Response, next: NextFunction) {
  if (req.headers.host == `v1.${process.env.SERVER_DOMAIN}`) req.url = `/v1${req.url}`; // ? <= direct from v1 to domain/v1
  if (req.headers.host == `api.${process.env.SERVER_DOMAIN}`) req.url = `/api${req.url}`; // ?  <= direct from v1 to domain/api

  next();
}); //Port is important if the url has it
Chukwuemeka Maduekwe
  • 6,687
  • 5
  • 44
  • 67