如何为Node.js应用程序设置本地子域

问题描述 投票:12回答:4

我正在node.js上运行一个快速应用程序。该应用程序使用express-subdomain module来帮助处理两个不同子域(sub1.example.com和sub2.example.com)的路由。我在AWS Elastic Beanstalk上托管应用程序。在我的生产环境中,一切都很棒。但是在我的本地机器上,我无法让它工作。我尝试将子域添加到我的主机文件127.0.0.1 localhost sub1.localhost sub2.localhost。虽然这允许我将子域添加到localhost,但模块不会将其识别为有效的子域,因此在我的根路由中搜索子域路由。

在main.js中:

var routes = require('./routes/index')(passport);
var sub1_routes = require('./routes/sub1')(passport);
var sub2_routes = require('./routes/sub2')(passport);

app.use(subdomain('sub1', sub1_routes));
app.use(subdomain('sub2', sub1_routes));
app.use('/', routes);

我需要能够在本地处理这个问题。将一个小的更改推送到AWS测试,迭代等需要花费很多时间。

node.js express localhost subdomain
4个回答
23
投票

我是模块的作者:)

对于您希望在本地测试的每个新子域,必须添加到/ etc / hosts文件中。例如:

localhost是:

127.0.0.1       localhost

一个新的子域名将是......

127.0.0.1       sub1.localhost

和另一个..

127.0.0.1       sub2.localhost

看看我在tests做了些什么。


8
投票

我有同样的问题,我找到了一个简单的解决方案。而不是写sub1.localhost尝试用localhost替换lvh.me这是一个总是解析为localhost的域,现在每当你写sub1.lvh.me,即使像sub1.lvh.me:3000这样的端口它仍然可以工作。


0
投票

在Ubuntu上

要为localhost创建子域,您只需执行2个简单步骤即可。

CTRL + ALT + T打开终端,然后运行以下命令:

sudo vi hosts
sudo -i gedit /etc/hosts # to edit /etc/hosts file

一旦运行第二个命令,/etc/hosts文件将打开,现在这是您需要定义子域的地方。

示例:localhost是:

127.0.0.1       //our localhost

define new subdomain:
127.0.0.1       example.localhost   # first

和另一个..

127.0.0.1       demo.localhost      #second

而已。希望这有用。


0
投票

有一个很棒的网站,有人托管给我们所有人。

local test.么

所有请求都将路由到127.0.0.1,包括子域。例如something.localtest.me:3000将决定127.0.0.1:3000

但是,例如,在你的Express应用程序中,如果你这样做

 app.get('*', (req, res) => {
     console.log(req.subdomains); // [ something ]
 });

你会得到你的子域名

© www.soinside.com 2019 - 2024. All rights reserved.