San Tosh San Tosh - 1 month ago 18
Node.js Question

NodeJS - Multiple Router files

I have 2 router files. One is for view routing and other for api requests.

I am trying to set the routing using:

var routes = require('./routes/index'); //View Router
var api = require('./routes/api'); //API Router

app.use('/', routes);
app.use('/api', api);


This fails in case of /api requests. If I remove one of the routings, the other works.

I also tried,

routes(app);
api(app);


But this fails too. Any idea what might be the issue? Please let me know in case additional details are required.

routers/index.js

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

var Promise = require('bluebird');
var nforce = require('nforce');
var org = require('../lib/connection');

/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'App' });
});

router.get('/accounts', function(req, res, next){
console.log(org);
res.render('partials/' + name);
org.query({query: 'Select Id, Name, Type, Industry, Rating From Account Order By LastModifiedDate DESC'})
.then(function(results){
console.log(results);
res.render('accounts', {title: 'Accounts', records: results.records});
});
});

router.get('/partials/:name', function(req, res, next){
var name = req.params.name;
console.log(name);
res.render('partials/' + name);
});

router.get('/api/:name', function(req, res, next){
var name = req.params.name;
console.log(name);
res.render('api/' + name);
});
module.exports = router;


/routers/api.js

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

var Promise = require('bluebird');
var nforce = require('nforce');
var org = require('../lib/connection');

/* GET home page. */
router.get('/getAccounts', function(req, res, next) {
console.log('in API router...');
org.query({query: 'Select Id, Name, Type, Industry, Rating From Account Order By LastModifiedDate DESC'})
.then(function(results){
console.log(results);
res.json({'accounts': results.records});
});
});
module.exports = router;

Answer

Maybe wrong but i see problem in this route.

router.get('/api/:name', function(req, res, next){})

It will match /api/cuteName and it also will match /api/getAccounts.

So you need to make routes more clear. I would suggest to change route inside index.js to be all something like /main/.

And all API routes move to api.js.

Hope this helps.

Comments