我正在尝试扩展 app.get 行为,但似乎在执行此操作后,应用程序会丢失我在扩展之前所做的一些配置。
在以下代码段中, / sample 和 / es / sample 输出为空,预期输出应为'值“
我做错了吗?
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);
};
答案 0 :(得分:1)
在您的代码中,您使用一个参数破坏了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);