如何配置Express响应对象来自动添加属性到JSON? [英] How to configure the Express response object to automatically add attributes to JSON?
问题描述
我有一个对象:
var obj = {stuff:stuff}
在Express中,我发送客户端:
res.json(OBJ);
有没有办法配置响应对象来自动添加属性到生成的json?例如,输出:
{
status:ok,
data :{stuff:stuff}
}
谢谢!
一旦数据被添加到流中,这太迟了,无法重新包装,所以你必须这样做。
只需一个函数:
res.json(wrap(obj)) ;
您还可以添加自己的json方法
express.response.wrap_json = function(obj){
this.json(wrap(obj));
};
所以你现在可以调用
res.wrap_json(OBJ);
或者您可以用您的代替替换express json实现
var original = express.response.json;
express.response.json = function(obj){
original.call(this,wrap(obj));
};
如果你想覆盖所有的json调用,我只会使用最后一个。
I have an object:
var obj = { "stuff": "stuff" }
In Express, I send it the client like so:
res.json(obj);
Is there a way to configure the response object to automatically add attributes to the json it generates? For example, to output:
{
"status": "ok",
"data": { "stuff": "stuff" }
}
Thanks!
Once the data has been added to the stream, that's too late to rewrap it, so you have to do it before.
Either simply with a function:
res.json(wrap(obj));
You could also add your own json method
express.response.wrap_json = function(obj) {
this.json(wrap(obj));
};
so you can now call
res.wrap_json(obj);
Or you could replace express json implementation with yours
var original = express.response.json;
express.response.json = function(obj) {
original.call(this, wrap(obj));
};
I would only use the last one if you want to override all json calls.
这篇关于如何配置Express响应对象来自动添加属性到JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!