Express和子域名(无静态文件)

使用nodejs和express处理子域的最佳做法是什么?

每个子域不会像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')); }); 

一种select是运行两个不同的节点应用程序。

如果你想在同一个节点的应用程序,你将不能有多个/ *路线。 只有第一个会受到打击。 一个不错的select是在其前面放置一个反向代理,并使用path将域名路由回节点应用程序。 这有其他的好处,如在Linux上没有你的端口80应用程序运行在sudo下

例如,在node-http-proxy中 , 他们添加了通过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是另一个反向代理选项。

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

 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' } }; 

这是一个很好的介绍。