【问题标题】:Express middleware to wrap responseExpress 中间件包装响应
【发布时间】:2015-11-05 18:05:20
【问题描述】:

我正在实现一个 API,其中结果需要由结果键返回,因此

{
  result: [
    {
      id: 1,
      name: "Bob"
    }
  ]
}

我想做的是添加一个中间件(如果可能的话),它可以包装每个响应,而不必每次都考虑它。实现这一目标的最佳方法是什么?我可以看到修改response.body,然后调用next() 而不是res.send(obj)(我现在正在做的事情)。

谢谢!

【问题讨论】:

标签: node.js express


【解决方案1】:

我最终扩展了响应对象以添加一个新函数(如 res.sendWrapped(data))每个 In Express and Node.js, is it possible to extend or override methods of the response object? 像这样:

express.response.sendWrapped = function(obj) {
    return this.send({ result: obj });
};

【讨论】:

    猜你喜欢
    • 2018-04-21
    • 2016-07-29
    • 1970-01-01
    • 2019-04-12
    • 2014-07-06
    • 2016-12-24
    • 2017-02-24
    • 1970-01-01
    • 2021-03-13
    相关资源
    最近更新 更多