Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express js:multiple route files into single file

In my express.js application i am organizing my routes in following way

routes/comment.js(handle all the comment routes)

var express = require('express');
var router = express.Router();
var comment = require('../controller/comment');
router.route('/new').get(comment.create);
module.exports = router;

routes/post.js(handle all the post routes)

var express = require('express');
var router = express.Router();
var post = require('../controller/post');
router.route('/new').get(post.create);
module.exports = router;

And i am including in app.js file like this way

//need to include these declarations into another file and include that file here
  //eg: require('config/main-routes');

    /*
     routes like comment/new
    */
    var comment  = require('./routes/comment');
    app.use('/comment',comment);
    /*
     routes like post/new
    */
    var post  = require('./routes/post');
    app.use('/post',post)

This works fine however i want to include this into another file lets say config/route-main.js and link this to app.js file

How can i do that??

like image 976
shellakkshellu Avatar asked Mar 08 '23 16:03

shellakkshellu


2 Answers

in app.js include

var routes  = require('./config/route-main');
app.use('/',routes);

and in route-config.js

var express = require('express');
var router = express.Router();
var comment  = require('./routes/comment');
var post  = require('./routes/post');

router.use('/comment',comment);
router.use('/post',post)


module.exports = router

check this link:

https://katieleonard.ca/blog/2016/2016-04-12-nested-routes-with-expressjs/

like image 53
Rishabh Mishra Avatar answered Mar 20 '23 11:03

Rishabh Mishra


Your app.js file:

const Express = require('express');
const app = Express();

const Routes = require('./routes');
app.use('', Routes);

Your routes.js file:

const Express = require('express');
const Router = Express.Router();

const UsersController = require('./controllers/usersController');

Router.post('/users', UsersController.CreateUser);

module.exports = Router;

Your usersController.js file:

const CreateUser = (req, res, next) => {
  // DO STUFF HERE
}

module.exports = {
  CreateUser
}
like image 27
Koray Gocmen Avatar answered Mar 20 '23 10:03

Koray Gocmen