【问题标题】:How to create a Restify middleware that modifies the response.body?如何创建修改 response.body 的 Restify 中间件?
【发布时间】:2017-05-13 00:07:53
【问题描述】:

我需要构建一个 restify 中间件,该中间件对处理程序产生的响应主体进行操作。似乎我传递给 server.use 的任何东西都被称为 before 处理程序。

我尝试调用next(),然后检查res 对象,但没有成功。

另外,这个answer 可能是我想要的,但我真的不需要use 路由器,我也不知道该怎么做。

【问题讨论】:

    标签: middleware restify


    【解决方案1】:

    您可以使用格式化程序。

    我认为使用中间件是行不通的。一旦找到合适的路由处理程序(.get .put .post 等),Restify 就会忽略中间件。您可以改用格式化程序。 http://restify.com/#content-negotiation

    当你创建一个 restify 服务器时,你可以指定格式化程序。这些是在路由处理程序调用 res.send() 之后调用的。这将允许您在将其送回之前对其进行操作。

    var server = restify.createServer({
      formatters: {
        'application/foo': function formatFoo(req, res, body, cb) {
             // body is what was sent with the response, you can edit it here.
             // You finish processing by calling cb(null, body).  
             // Just be sure that you body is properly stringified.
             // See the restify docs above for more information.
        }
      }
    });
    

    【讨论】:

    • 有没有办法从自定义的格式化程序中调用默认格式化程序?
    • 我不这么认为。文档中提供的示例格式化程序是默认格式化程序,因此您可以将自定义逻辑附加到该格式化程序。
    猜你喜欢
    • 2012-04-11
    • 2015-06-16
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2017-12-16
    • 2010-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多