gpt4 book ai didi

node.js - 使用自定义方法扩展 ExpressJS/Response 对象的正确方法是什么?

转载 作者:搜寻专家 更新时间:2023-11-01 00:43:33 25 4
gpt4 key购买 nike

现在我通过中间件扩展请求对象:

function(req, res, next) {
res.customMethod = function() {

}
next();
}

但我认为由于 res.prototype 命名空间的污染,这是不正确的。有没有人知道更好的方法或者 expressjs4 已经有任何方法可以解决这个问题?

最佳答案

您的方法几乎是完美的,但正如您所说,最好避免污染 res 命名空间:要达到您的目标,您可以使用为此设计的 res.locals 属性。下面是一个片段,其中我将我的应用程序的翻译器附加到响应对象。

app.use(function(req, res, next){

function Translator (lang) {
this.lang = lang ? lang : 'it';

this.translate = function (sentence) {
var d = dictionaries.get;

var translation = d[this.lang] ? d[this.lang][sentence] : d['it'][sentence];
return translation ? translation : sentence;
};
this.setLang = function (l) {
this.lang = l;
};
};

res.locals.translator = new Translator();
next();
});

关于node.js - 使用自定义方法扩展 ExpressJS/Response 对象的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26649821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com