首页 > 解决方案 > Monkey Patch 在发送响应之前重新调整响应

问题描述

我正在尝试在我的restify json响应中应用 JSON 掩码(与 Friday 13th 游戏或电影无关) 。

正常的做法是在所有服务器路由中调用 next(),然后在 restify 的 'pre' 处理程序中实现掩码

我现在不能这样做,我要快速修复,所以我正在尝试猴子修补我的 restify 响应,如下所示:

创建一个模块“CustomResponse”:

function CustomResponse (originalResponse) {
  this.restifyResponse = originalResponse
  this.type = 'customResponse'
}

CustomResponse.prototype.send = function (code, payload) {
  if (!payload) { payload = code }

  console.log(payload)  
  this.restifyResponse.send(code, payload)
}

module.exports = CustomResponse

我正在尝试在中间件中使用此模块,但它不起作用:

  var CustomResponse = require('./customResponse') // the file above

  server.use(function (req, response, next) {
    response = new customResponse(response)
    next()
  })

这仅在我在路线中使用时才有效:

 var CustomResponse = require('./customResponse') // the file above

 server.get({
   path: '/foo/bar'
 }, function(request, response, next){
     response = new CustomResponse(response)
     response.send('baz') // this will print on the console the response and send it to the browser
 })

感谢您的任何提示!

标签: node.jsrestify

解决方案


这是你的中间件?

 var CustomResponse = require('./customResponse') // the file above

  server.use(function (req, response, next) {
    response = new Response(response)
    next()
  })

对于此代码:

response = new Response(response)

我认为你应该像下面的代码一样使用它

response = new CustomResponse(response)

因为您使用的变量是CustomResponse,不是Response

我希望它有帮助。


推荐阅读