Express Routes - Issues with multiple files

I'm starting to learn Node.js with Express, but i've got few issues with the routing system.

In my app.js (my main file), i have :

var express = require('express');
var path = require('path');
var routes = require('./routes/index');
var admin = require('./routes/admin');
...
app.use('/', routes);
app.use('/admin, admin);

In the index.js :

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

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', {
    title: 'Express'
  });
});

The root url work great, and it return correctly the jade template 'index'.

I'm trying to do the same thing, in a different file, for an 'admin' template (wich is in './routes/admin'). There is the point, when i go to the localhost:5000/admin (for exemple), it return a 404 error.

There is my admin.js file :

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

router.get('/admin', function(req, res, next) {
  res.render('admin', {
    title: 'Connexion'
  });
});

Both of index.js and admin.js contain module.exports = router;

If someone got an idea or want to comment, you're welcome.

Thanks a lot (and forgive my english !)

Your problem might be that you are instantiating multiple instances of express and its Router, one in each routes file. You'll want one Router in your app.js file, and each of the separate routes file should refer to this single instance.

As one idea, you could pass in your router in app.js to each of your routes files:

// app.js
var admin = require('./routes/admin');
admin.init(router);

And then in your admin.js file:

var init = function(router) {
  exports.router = router;

  exports.router.get('/admin', function(req, res, next) { 
    // ...
  });
}

You are trying to route this page localhost:5000/admin/admin. app.use('/admin, admin); means that all function in admin.js will be called by this request localhost:5000/admin/... So If you want to render admin.jade with this request localhost:5000/admin, you should insert this function in routes/index

router.get('/admin', function(req, res, next) {
  res.render('admin', {
    title: 'Connexion'
  });
});

or in routes/admin insert this function:

router.get('/', function(req, res, next) {
  res.render('admin', {
    title: 'Connexion'
  });
});