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??
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/
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With