Express和子域(没有静态文件)

时间:2014-01-23 01:11:51

标签: node.js 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'));
});

1 个答案:

答案 0 :(得分: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是一个很好的介绍。