最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to configure the Express response object to automatically add attributes to JSON? - Stack Overflow

programmeradmin0浏览0评论

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!

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!

Share Improve this question edited May 25, 2023 at 11:31 aynber 23k9 gold badges54 silver badges67 bronze badges asked Feb 1, 2013 at 22:17 user1031947user1031947 6,67417 gold badges65 silver badges91 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

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.

发布评论

评论列表(0)

  1. 暂无评论