简体   繁体   中英

express-subdomain not redirecting subdomain.localhost get request

I am using an express.js package called express-subdomain to facilitate requests to defined subdomains I set up.

As far as I understand, the subdomain constructor function expects an express router object which I pass to it from an exported router module.

What I have tried is as follows:

MAIN APP.JS SERVER FILE

var common = {
    express: require('express'),
    subdomain: require('express-subdomain')

};

common.app = common.express();

module.exports = common;

common.app.listen(3000, function () {
  console.log(('app listening on http://localhost:3000'));
});

var router = require('./router/index');


// Error Handling
common.app.use(function(err, req, res, next) {
    res.status(err.status || 500);
});

router/index

 module.exports = function (){
        var common = require('../app');
        var router = common.express.Router();

        common.app.get('/', function(req, res) {
        res.send('Homepage');
        });


        common.app.use('/signup', require('./routes/signup'));
        common.app.use(common.subdomain('login', require('./routes/login')));
    }();

routes/login

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


router.get('/', function (req, res) {
    res.send('login working');
});


router.get('/info', function (req, res) {

});
module.exports = router;

I have tried to access the login subdomain at the following urls:

http://login.localhost
http://login.localhost:3000
http://login.localhost.com
http://login.localhost.com:3000

Any clarification or assistance appreciated.

author of express-subdomain here 👋

A couple of things:

  1. Hosts must be setup correctly - I'd recommend something like so in your /etc/hosts file.

127.0.0.1 myapp.local 127.0.0.1 login.myapp.local For more information on this see https://github.com/bmullan91/express-subdomain#developing-locally

  1. Register the subdomain routes before any others, including the homepage route. The order is very important

  2. The pattern you're using in /routes/index.js is not advised (requiring a self invoking function). Exporting the Router like you done in /routes/login.js is cleaner.

Finally, If you're still stuck take a look at the source for express subdomain and in particular its tests.

Happy coding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM