2014-01-23 21 views
1

处理nodejs和表达子域的最佳做法是什么?表达式和子域名(无静态文件)

每个subsomain不会静态文件等的index.html等,但纯的代码和逻辑

var express = require('express'), 
    http = require('http'); 

var app = express(); 
app.set('port', 8080); 
app.set('case sensitive routing', true); 

// Catch api.localhost 
app.get('/*', function(request, response){ 
    /* 
     Other logic 
    */ 
    response.end('API'); 
}); 

// Catch www.localhost 
app.get('/*', function(request, response){ 
    /* 
     Other logic 
    */ 
    response.end('WEB'); 
}); 

http.createServer(app).listen(app.get('port'), function(){ 
    console.log('Express server listening on port '+app.get('port')); 
}); 
+0

我已经在这里回答了一个类似的问题:http://stackoverflow.com/questions/5791260/how-can-i-configure-multiple-sub-domains-in-express-js-or-connect-js/23324995 #23324995 – bmullan91

回答

2

一种选择是具有运行两个不同的节点的应用程序。

如果你想在同一个节点的应用程序,你将无法拥有多个/ *路线。只有第一个会被击中。一个不错的选择是在其前面放置一个反向代理,并使用路径将域名路由回节点应用程序。这有一个像Linux上的not having your port 80 apps run under sudo

例如其他的好处,在node-http-proxythey added the ability to route the proxy by path

var options = { 
    router: { 
    'api.myhost.com': '127.0.0.1:8080/api', 
    'myhost.com': '127.0.0.1:8080', 
    'www.myhost.com': '127.0.0.1:8080' 
    } 
}; 

然后在8080上运行的节点的应用程序将有路线:

'/api/*' --> api code 
'/*' --> web 

nginx的是另一个反向代理选项。

我可能会为前端和后端运行两个不同的节点进程并将其隐藏在代理之后。保持每次清理的代码并允许您独立调整和配置它们,而无需更改代码。

var options = { 
    router: { 
    'api.myhost.com': '127.0.0.1:8080', // note different app on diff port 
    'myhost.com': '127.0.0.1:8090', 
    'www.myhost.com': '127.0.0.1:8090' 
    } 
}; 

Here是一个很好的介绍。