Extension of app.get express method in nodejs application

I am trying to extend the behavior of app.get , but it seems that after this the application lost some configuration that I did before expanding it.

In the following snippet / sample and / es / sample, the output is empty and the expected result should be '

Am I doing something wrong?

var app = require('express')(); app.set('myprop', 'value'); var _get = app['get']; app['get'] = function (route, middleware, callback) { _get.call(app, route, middleware, callback); // For instance: I generate a new route for 'es' language. _get.call(app, '/es' + route, middleware, callback); }; app.get('/sample', function(req, res){ res.send(app.get('myprop')); }); app.use(app.router); app.listen(3000); 

UPDATE

Sorry, I will answer myself ...

I skipped the next first line in the extension method :)

 if (middleware === undefined && callback === undefined) return _get.call(app, route); 

Now it works like a charm!

 app['get'] = function (route, middleware, callback) { if (middleware === undefined && callback === undefined) return _get.call(app, route); _get.call(app, route, middleware, callback); // For instance: I generate a new route for 'es' language. _get.call(app, '/es' + route, middleware, callback); }; 
+6
source share
1 answer

In your code, you break the behavior of app.get with one argument. Try the following:

 var app = require('express')(); app.set('myprop', 'value'); var _get = app['get']; app['get'] = function (route, middleware, callback) { if (arguments.length > 1) { _get.call(app, route, middleware, callback); // For instance: I generate a new route for 'es' language. _get.call(app, '/es' + route, middleware, callback); } else { return _get.apply(app, arguments); } }; app.get('/sample', function(req, res){ res.send(app.get('myprop')); }); app.use(app.router); app.listen(3000); 
+1
source

All Articles