How to set up local subdomains for Node.js app

∥☆過路亽.° 提交于 2020-01-12 03:16:12

问题


I am running an express app on node.js. The app uses the express-subdomain module to help handle routes for two different subdomains (sub1.example.com and sub2.example.com). I'm hosting the app on AWS Elastic Beanstalk. In my production environment, everything works great. But on my local machine, I cannot get this to work. I tried adding the subdomains to my host file 127.0.0.1 localhost sub1.localhost sub2.localhost. Although that allows me to prepend a subdomain to localhost, the module doesn't recognize this as a valid subdomain, and therefor searches for subdomain routes in my root routes.

In 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);

I need to be able to handle this locally. It takes to much time to push a small change to AWS test, iterate, etc.


回答1:


I'm the author of the module :)

For each new subdomain you wish to test locally you must add into your /etc/hosts file. So for example:

localhost is:

127.0.0.1       localhost

a new subdomain would be..

127.0.0.1       sub1.localhost

and another..

127.0.0.1       sub2.localhost

Check out what I have done in the tests.




回答2:


I had same exact problem and I found a simple solution. Instead of writing sub1.localhost try replacing localhost with lvh.me this is a domain that always resolves to localhost and now whenever you write sub1.lvh.me even though a port like sub1.lvh.me:3000 it will still work.




回答3:


on Ubuntu

For creating subdomains for localhost you just need to follow 2 simple steps.

Open your terminal by pressing CTRL + ALT + T then run the following commands:

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

Once you run 2nd command /etc/hosts file will open and now this is the place where you need to define subdomains.

Example: localhost is:

127.0.0.1       //our localhost

define new subdomain:
127.0.0.1       example.localhost   # first

and another..

127.0.0.1       demo.localhost      #second

that's it. Hope this was helpful.




回答4:


There is an awesome website, which someone hosted for all of us.

localtest.me

All requests will be routed to 127.0.0.1, including subdomains. e.g something.localtest.me:3000 will resolve to 127.0.0.1:3000

but, for example, in your Express app, if you do

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

you'll get your subdomain



来源:https://stackoverflow.com/questions/26564961/how-to-set-up-local-subdomains-for-node-js-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!