Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Extending express app.get method in a nodejs app

Extending express app.get method in a nodejs app

Problem

I'm trying to extend the app.get behavior but it seems that after doing it, the app losses some configuration I did before extending it.

In the following snippet the /sample and /es/sample output are empty and the expected output should be 'value'

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 missed the following 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);
};
Problem courtesy of: user1796747

Solution

In your code you are broke app.get behaviour with one argument. Try this:

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);
Solution courtesy of: Vadim Baryshev

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Extending express app.get method in a nodejs app

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×