【问题标题】:Monkey Patch restify response before sending the responseMonkey Patch 在发送响应之前重新调整响应
【发布时间】:2019-05-19 00:49:02
【问题描述】:

我正在尝试在我的 restify json response 上应用 JSON 掩码(与 13 日星期五的比赛或电影无关)。

正常的做法是在所有服务器路由中调用 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.js restify


    【解决方案1】:

    这是你的中间件?

     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。

    希望对你有帮助。

    【讨论】:

    • 感谢titus,这是一个错字,但仍然无法正常工作......好像我无法修改中间件与请求中的响应对象
    • 我不知道为什么它对你不起作用,但我已经尝试过了,我可以在这里做到。错误信息是什么?
    猜你喜欢
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    • 2020-04-20
    • 2012-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多