Reputation: 1302
I separated routes for rest api like this. Is there better way to organize router ? or the way I am doing is fine?
app.js
app.use('/api/auth',auth);
app/controllers/auth/index.js
var express = require('express'),
router = express.Router(),
register = require('./register');
router.get('/',function(req,res,next){
console.log("api/auth");
res.send('api/auth');
next();
});
router.use('/register',register);
module.exports = router;
app/controllers/auth/register.js
var express = require('express'),
router = express.Router(),
rootPath = require('app-root-path'),
User = require(rootPath+'/app/models/user');
router.post('/',function(req,res,next){
console.log("api/auth/register");
next();
});
module.exports = router;
Upvotes: 0
Views: 76
Reputation: 650
Building on swaraj'a answer, you should divide your project files into two folders lib and config. Please note that I'm giving you a generic structure this should be customised according to your project.
Config
It should contain all the configuration files for your project.
lib
It should basically have files like controller.js
, routes.js
, db-ops.js
controller.js contains and exports all functions required for your program logic.
routes.js contains and exports all the routes
db-ops.js intializes db connections and contains functions that define operations on database.
All these files should be required into your app.js which will reside in your projects root directory.
A typical project structure should look something like this:
lib
-routes.js
-controller.js
-db-ops.js
config
-config.json
app.js
Upvotes: 1
Reputation: 4037
You could create a routes.js
which has all the separate routes.
Something like,
module.exports = function (app) {
app.use('/api/route1', require('path/to/route1'));
app.use('/api/route2', require('path/to/route2'));
};
Mount this routes in your main app.js
.
require('path/to/routes')(app);
Shameless plug of an example, https://github.com/swarajgiri/express-bootstrap/blob/master/web/routes.js
Upvotes: 0