Alvin
Alvin

Reputation: 8499

Module route separation

When I use http://tes.com/routes, it will route to the api=>get('/'), instead of web=>get('/'). Why?

app.js:

var api = require('./app/routes/routes').api;
var transaction_web = require('./app/routes/routes').web;

app.use('/api/routes', transaction_api);
app.use('/routes', transaction_web);

routes.js:

var api = (function () {
    router.get('/', function (req, res, next) {
       ...
    });

    return router;
})();

var web = (function () {
    router.get('/', function (req, res, next) {
       ...
    });

    return router;
})();

module.exports = {
    api: api,
    web: web
};

Upvotes: 1

Views: 110

Answers (1)

mscdex
mscdex

Reputation: 106696

The reason is because that's the order in which you're adding the routes.

This:

var api = (function () {
  router.get('/', function (req, res, next) {
     ...
  });

  return router;
})();

is the same as:

router.get('/', function (req, res, next) {
  ...
});
var api = router;

The same thing happens with the other block where you assign web, so you end up with:

router.get('/', function (req, res, next) {
  // api route
});
var api = router;
router.get('/', function (req, res, next) {
  // web route
});
var web = router;

The solution would be to create separate Router instances. For example:

var api = new express.Router();
api.get('/', function (req, res, next) {
  // web route
});

var web = new express.Router();
web.get('/', function (req, res, next) {
  // web route
});

Upvotes: 1

Related Questions