user4815703
user4815703

Reputation:

Express-subdomain routing not working correctly?

I have been looking for solutions for a couple days now trying to google it and all and now i am here. I am trying to setup subdomains for my app using express-subdomain package. However in the example below the app ALWAYS returns app.get route and skips the other subdomain routes specified. I have also in turn added the hosts file url so i know that should not be the issue.

It must be in my code for some reason it always ends up displaying Detect Region route even when accessing oce.localhost:3000.

Please help me :)

Server.js

var subdomain = require('express-subdomain');
var express = require('express');
var app = express();

// Region routes
var router = express.Router();
var na = require('./routes/region/na.js');
var oce = require('./routes/region/oce.js');

router.use(subdomain('na.localhost', na));
router.use(subdomain('oce.localhost', oce));

app.get('/', function(req, res) {
    res.send('Detect Region and send to correct subdomain!');
});

app.listen(3000);

routes/region/oce.js

var
  express = require('express'),
  router = express.Router();

router.get('/', function(req, res) {
    res.send('Your are in OCE Region!');
});

module.exports = router;

And na.js is pretty much the name as oce.js

Cheers

Upvotes: 0

Views: 1198

Answers (1)

Telokis
Telokis

Reputation: 3389

You are setting your subdomains in the router variable but you don't tell your app to use it.

You have to do that :

app.use(router);

You put it in place of your current app.get.


Edit

You could also put your app.get after the app.use(router) so that it will act as a default route. (When you are neither on oce or na, it will use it)


Edit after some testing

Alright I've been able to make it work using express-vhost. I just updated your server.js like so :

var subdomain = require('express-vhost');
var express = require('express');
var app = express();

// Region routes
var router = express.Router();
var na = require('./routes/region/na.js');
var oce = require('./routes/region/oce.js');

subdomain.register('na.localhost', na)
subdomain.register('oce.localhost', oce)

app.use(subdomain.vhost(app.enabled('trust proxy')));

app.get('/', function(req, res) {
    res.send('Detect Region and send to correct subdomain!');
});

app.listen(3000);

Upvotes: 0

Related Questions