Specifying a Subdomain in Route Definition in Express

I am new to ExpressJS and NodeJS in general, so I need guidance on how to achieve this effect:

app.get('/', 'sub1.domain.com', function(req, res) { res.send("this is sub1 response!"); }); app.get('/', 'sub2.domain.com', function(req, res) { res.send("this is sub2 response!"); } 

So, when I request sub1.domain.com , the first handler responds, and on sub2.domain.com I get a response from the second handler. I read some questions about SO about using vhost for this purpose, but I would be happier if what I described above worked, rather than creating multiple server instances, for example in vhost.

+4
source share
2 answers

Quick and easy solution:

 app.get('/', function(req, res) { var hostname = req.headers.host.split(":")[0]; if(hostname == "sub1.domain.com") res.send("this is sub1 response!"); else if(hostname == "sub2.domain.com") res.send("this is sub2 response!"); }); 

Link:

http://code4node.com/snippet/http-proxy-with-custom-routing

+9
source

Or you can just use the npm subdomain package, it takes care of your subdomain routes. It also looks like you can check out the Wilson project on a subdomain-handler .

+7
source

Source: https://habr.com/ru/post/1500357/


All Articles