node.js - 在 nodejs 应用程序中扩展 express app.get 方法

标签 node.js express

我正在尝试扩展 app.get 行为,但似乎在执行此操作后,应用程序丢失了我在扩展它之前所做的一些配置。

在以下代码段中,/sample/es/sample 输出为,预期输出应为'value '

我做错了什么吗?

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);

更新

对不起,我会自己回答...

我错过了扩展方法中的以下第一行:)

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

现在它就像一个魅力!

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);
};

最佳答案

在您的代码中,您用一个参数破坏了 app.get 行为。试试这个:

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);

关于node.js - 在 nodejs 应用程序中扩展 express app.get 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13211156/

相关文章:

node.js - 如何使用 node.js 在 Windows Azure 上修复 "Port 80 requires elevated privileges"?

angularjs - nodemon 应用程序崩溃 - 在启动之前等待文件更改

node.js - 在 mongoose 中创建数据时无法读取未定义的属性 'push'

mysql - 当 NodeJS 中不存在记录时捕获 MySQL 错误

javascript - Passport JS - 一张登录表单 - 根据用户角色重定向到不同的 URI

javascript - 在javascript中类型检查自定义对象

node.js - 更新 Mongoose 中的对象会导致循环

javascript - 如何在nodejs中裁剪屏幕截图或图像(.png)?

javascript - Node.js + Express - 无法连接。 ERR_CONNECTION_REFUSED

javascript - Node Js 实际上是异步的吗?