Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS Express multiple route file through one route file

I am learning NodeJS. I have a nodeJS API project. I want to use version in routes so i created following folder structure.

application/    
    --app.js
    --routes/
    ----V1/
    ------routes.js
    ------users.js

Here is my app.js file:

 var v1 = require('./routes/v1/route');

 app.use('/api/v1', v1.router);

And this is route.js file:

var express = require('express');
var router = express.Router();
router.get('/',function(req,res){    
    res.send("Welcome to Node JS V1");
});

var courses = require('./users').router;
-- How to include usres route here

module.exports.router = router;

users.js file:

var express = require('express');
var router = express.Router();
router.get('/',function(req,res){    
    res.send("Get all users.");
});


module.exports.router = router;

Now how i can call users from route.js file.

like image 955
Sid Avatar asked Dec 16 '16 10:12

Sid


2 Answers

I'd do it a bit different than @Shaharyar

routes.js

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

router.get('/', function(req, res) {
  res.send('Welcome to Node JS V1');
});

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

module.exports.router = router;

users.js

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

router.get('/',function(req, res){    
  res.send('Get all users.');
});

router.post('/', function(req, res) {
  // Create user
  res.send('Some response.');
});

module.exports.router = router;

To simplify it I'd drop the .router on module.exports and do.

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

Also the same for the route.js file, then in your server.js or wherever:

router.use('/api/v1', require('./routes'));
router.use('/api/v2', require('./routes2'));
like image 141
Jordonias Avatar answered Sep 20 '22 10:09

Jordonias


You should create express instance once and pass it into all modules.

route.js file

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

router.get('/', function(req, res){    
    res.send("Welcome to Node JS V1");
});

//modules
require('./users')(router);
require('./sessions')(router);  //added for explaination
require('./comments')(router);  //added for explaination

//export
module.exports.router = router;

module file (any module users, comments etc)

//initialize
module.exports = function (router) {
    router.get('/users', users);
}

//APIs
function users(req, res) {    
    res.send("Get all users.");
}
like image 27
Shaharyar Avatar answered Sep 19 '22 10:09

Shaharyar