Specifying a subdomain in the route definition in Express

懵懂的女人 提交于 2019-12-04 23:56:53

问题


I'm new to ExpressJS and NodeJS in general, so I need directions 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 that when I request sub1.domain.com the first handler reacts and on sub2.domain.com I get response from second handler. I've read some questions on SO about using vhost for this purpose, but I'd be more happy if what I described above worked rather than creating multiple server instances like in vhost.


回答1:


A quick and simple solution is:

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!");

});

Reference:

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




回答2:


Or you can simply use npm package subdomain, it take cares of your subdomain routes. Also similar to that you can check out Wilson's project on subdomain-handler.



来源:https://stackoverflow.com/questions/18598668/specifying-a-subdomain-in-the-route-definition-in-express

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