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

Acu*_*ute 5 subdomain node.js 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!");
}
Run Code Online (Sandbox Code Playgroud)

因此,当我请求sub1.domain.com第一个处理程序作出反应时,sub2.domain.com我从第二个处理程序得到响应.我读过有关使用虚拟主机专门为此等等一些问题,但我会更高兴,如果我上述的工作,而不是创建多个服务器实例,就像在虚拟主机.

Jaz*_*zor 9

一个快速简单的解决方案是:

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

});
Run Code Online (Sandbox Code Playgroud)

参考:

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


Sus*_*pta 8

或者你可以简单地使用npm包子,它会照顾你的子域路由.也类似于你可以在子域处理程序上查看Wilson的项目.