bmullan91/express-subdomain

Not working...

LucGranato opened this issue · 4 comments

My server code is the following...

/* CÓDIGOS DE ERRO (lista completa em https://en.wikipedia.org/wiki/List_of_HTTP_status_codes) */
var util = require('util');

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

var mongoose = require('mongoose');
var bodyParser = require('body-parser');

var passport = require('passport');
var BasicStrategy = require('passport-http').BasicStrategy;

var User = require('./models/user');

// MongoDB
mongoose.connect('mongodb://localhost/remotelinkdb');

var api = express.Router();
var device = express.Router();
var mobile = express.Router();

// Passport Basic Authorization
passport.use(new BasicStrategy(

    function(userid, password, done) {

        User.findOne({ email: userid }, function (err, user) {

            if (err) { return done(err); }
            if (!user) { return done(null, false); }
            if (!user.verifyPassword(password)) { return done(null, false); }
            return done(null, user);
        });
    }
));


/*********************************** Router mobile *********************************/

mobile.use('/sendinstallation', function (req, res, next) {
    if (!req.body['installationId']) return res.status(400).send("Installation missing.");
    req.body['lastConnection'] = Date.now();

    mongoose.model('installation').findOne({'installationId' : req.body['installationId']})
        .then(function (installation) {

            if (installation) {
                installation.set(req.body);
                return installation.save();
            }

            var Installation = mongoose.model('installation');
            var newinstallation = new Installation(req.body);

            return newinstallation.save();

        }).then(function (savedInstallation) {

            return res.status(200).send(savedInstallation);

        }).catch(function (e) {

            util.error(e);
            return res.status(400).send('Error 1011');

        });
});

/***********************************************************************************/


/*********************************** Router device *********************************/

device.use('/', require('./routes/hardware')); //SEM AUTENTICAÇÃO POR ENQUANTO

/***********************************************************************************/


/*********************************** Router api *********************************/

api.use(passport.initialize());

// Passport Basic Authorization
passport.use(new BasicStrategy(

    function(userid, password, done) {

        User.findOne({ email: userid }, function (err, user) {

            if (err) { return done(err); }
            if (!user) { return done(null, false); }
            if (!user.verifyPassword(password)) { return done(null, false); }
            return done(null, user);
        });
    }
));

api.use('/', passport.authenticate('basic', { session: false}), require('./routes/api'));
api.use('/func', require('./routes/cloud'));

// Login
api.use('/login', function(req, res) {
    res.json(req.user);
});

// Static folder
api.use('/file', express.static('public/temp'));

/**********************************************************************************/

var app = express();

app.use(subdomain('api', api));
app.use(subdomain('device', device));
app.use(subdomain('mobile', mobile));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use('/', function(req, res) {
    var url = req.protocol + '://' + req.get('host') + req.originalUrl;
    res.send(url);
});

// Start server
app.listen(3000);
util.log("Server running on port 3000");

Does anyone know why it's not working?

Even when I call ( api.beetrack.com.br/login ) I get response from app.use('/', function(req, res) { ......

Thanks in advance!

Hi @LucGranato, great find!

It's because the it's a multi-level TLD (.com.br) - express splits the url by '.' and the last two items in the array are considered the 'host' - everything before them will be added to the req.subdomains array, which this module uses to check against.

Therefore, to make it work in your case, add '.beetrack' to the string you pass to subdomain:

app.use(subdomain('api.beetrack', api));
app.use(subdomain('device.beetrack', device));
app.use(subdomain('mobile.beetrack', mobile));

PS. I've wrote some tests to check that this works in #18. I'll make sure and update the readme describing this 😄.

Thanks a lot @bmullan91 !
It worked perfectly! Congrats..
Muito obrigado (from Brazil)..

MoLow commented

This could also be solved with subdomain offset in http://expressjs.com/en/4x/api.html#app.settings.table

@MoLow
Please I have some problem with express-subdomain
app.js
var express = require('express');
var router = express.Router();
var app = express();
var index = require('./routes/index');
app.use('/', index);
app.listen(3000);

and index.js

const
subdomain = require('express-subdomain'),
express = require('express'),
router = express.Router();

function init(server) {
server.use(subdomain('api', router))

server.get('/', function (req, res) {
    res.redirect('/home');
});

router.get('/', function(req, res) {
res.send('Welcome to our API!');
});
 
router.get('/users', function(req, res) {
	res.json([
		{ name: "Brian" }
	]);
});
	
server.get('*', function (req, res, next) {
    console.log('Request was made to: ' + req.originalUrl);
    return next();
});

}

module.exports = {
init: init
};

getting this error

throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
^

TypeError: Router.use() requires a middleware function but got a Object
at Function.use (C:\node\my-contract\node_modules\express\lib\router\index.js:458:13)
at Function. (C:\node\my-contract\node_modules\express\lib\application.js:220:21)
at Array.forEach ()
at Function.use (C:\node\my-contract\node_modules\express\lib\application.js:217:7)
at Object. (C:\node\my-contract\sub.js:17:5)
at Module._compile (module.js:635:30)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)