Blu Blu - 25 days ago 9
Node.js Question

Separation of routes in express

To prevent having a long list of routes in my routes.js file, I have moved routes.js into a folder simply called routes, and renamed the file to index.js. I want to create multiple other files that define routes for different categories. Here's the code that I would think I need to write to accomplish that:

// index.js
var express= require('express');
var app = express();
var passport = require('passport');

app.use('/api/auth', require('./auth.routes')(passport));
...


I required the auth routes, so now I can use them like this:

// auth.routes.js
var router = require('express').Router();

module.exports = function(app, passport) {
router.post('/login', function(req, res) {
...
});

router.get('/me', function(req, res) {
...
});
...
return router;
};


When I do this,
require('express').Router()
is undefined, I'm not sure why. What's the proper way to separate these routes?

Answer

Have a folder: routes

In /routes/index.js :

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

router.use('/api/auth', require('./auth'));
router.use('/api/users', require('./users'));

module.exports = router;

In /routes/auth.js :

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

router.post('/login', function(req, res) {
  ...
});

router.get('/me', function(req, res) {
  ...
});

module.exports = router;

In /index.js :

app.use(require('./routes')); // it will read /routes/index.js and it will read another files and build routing

p.s. use passport checkings in /routes/index.js (or separately in nested routing files) as middleware between route and require part.

if You want to see real example check this