在Express中的路由定义中指定一个子域

我一般都是ExpressJS和NodeJS的新手,所以我需要指导如何达到这个效果:

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

所以,当我请求sub1.domain.com第一处理程序反应,并在sub2.domain.com我从第二处理程序得到的响应。 我已经阅读了关于使用vhost来达到这个目的的一些问题,但是如果我上面描述的工作起来,我会更高兴,而不是像在vhost中那样创build多个服务器实例。

一个简单而快速的解决scheme是:

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

参考:

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

或者你可以简单地使用npm包子域 ,它照顾你的子域路由。 也类似于你可以看看威尔逊的子域处理程序的项目。