Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending express app.get method in a nodejs app

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);
};
like image 917
user1796747 Avatar asked Nov 03 '12 16:11

user1796747


People also ask

How do you call a post method in node JS?

Example code: var request = require('request') var options = { method: 'post', body: postData, // Javascript object json: true, // Use,If you are sending JSON data url: url, headers: { // Specify headers, If any } } request(options, function (err, res, body) { if (err) { console. log('Error :', err) return } console.


1 Answers

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);
like image 70
Vadim Baryshev Avatar answered Nov 02 '22 22:11

Vadim Baryshev