Reputation: 147
Here is the app.js file:
var express = require('express'),
routes = require('./routes'),
api = require('./routes/api.js'),
http = require('http'),
path = require('path');
var app= module.exports = express();
/**
* Configuration
*/
// all environments
app.set('port', process.env.PORT || 3001);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
// development only
if (app.get('env') === 'development') {
app.use(express.errorHandler());
}
// production only
if (app.get('env') === 'production') {
// TODO
};
/**
* Routes
*/
// serve index and view partials
app.get('/', routes.index);
// redirect all others to the index (HTML5 history)
app.get('*', routes.index);
api(app);
/**
* Start Server
*/
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
Here is the routes/api.js file:
var queryObj = {
retrieve:{
api_path:'/api/test/list',
var_name:''
}
};
// All supporting functions used below are defined here !
module.exports = function(app) {
_.each(queryObj, function(obj) {
console.log("Check point 1");
var args = [obj.api_path, function(req, res){
var search_term = obj.var_name ? req.params[obj.var_name] : '';
get(search_term,res);
}];
console.log("Check point 2");
console.log("args:" + args);
app.get.apply(app,args);
});
};
Here is the routes/index.js file:
/*
* GET home page.
*/
exports.index = function(req, res){
console.log("Default view");
res.render('index');
};
So when i run this application and type localhost:3001/api/test/list in the browser, i get follwing output on the console:
Check point 1
Check point 2
`args: args:/api/alarms/list,function (req, res){
var search_term = obj.var_name ? req.params[obj.var_name] : '';
get(search_term,res);
}`
Express server listening on port 3001 Default view
My question is: why is app.get.apply()
not working? Instead the default route configured in app.js is taken up!
Upvotes: 1
Views: 7631
Reputation: 2217
I think you need to change the order of your route definitions: from most specific (in this case api/test/list
to less specific *
:
// defined api
api(app);
// serve index and view partials
app.get('/', routes.index);
// redirect all others to the index (HTML5 history)
app.get('*', routes.index);
Upvotes: 2