How to configure the Express response object to automatically add attributes to JSON?

流过昼夜 提交于 2019-12-05 23:18:22

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/14655968/how-to-configure-the-express-response-object-to-automatically-add-attributes-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!