在ExpressJS中执行res.send()之前修改响应主体 [英] Modify response body before res.send() executes in ExpressJS

查看:70
本文介绍了在ExpressJS中执行res.send()之前修改响应主体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我当前开发的应用程序中,它正在使用Express.就我而言,我想在发送响应之前得到响应并进行修改(出于JWT的目的).在此应用程序中,有十二个端点,我不想创建自己的函数,例如 sendAndSign(),并在代码中的任何地方替换 res.send().我听说有选项可以覆盖/修改 res.send(...)方法的逻辑.

In application which I currently develop, it's using Express. In my case I want to get response before it's been sent and modify it (for purpose of JWT). In this application, there is a dozen of endpoints and I don't want to create my own function like sendAndSign() and replace res.send() everywhere in code. I heard there is option to override/modify logic of res.send(...) method.

我发现了这样的内容修改示例,但在我的情况下,此方法无效.还有其他选项(也许使用某些插件)来管理此操作吗?

I found something like this example of modifying, but in my case this doesn't work. Is there any other option (maybe using some plugin) to manage this action?

推荐答案

您可以通过临时覆盖 res.send :

function convertData(originalData) {
  // ...
  // return something new
}

function responseInterceptor(req, res, next) {
  var originalSend = res.send;

  res.send = function(){
    arguments[0] = convertData(arguments[0]);
    originalSend.apply(res, arguments);
  };
  next();
}

app.use(responseInterceptor);

我在Node.js v10.15.3中进行了测试,效果很好.

I tested in Node.js v10.15.3 and it works well.

这篇关于在ExpressJS中执行res.send()之前修改响应主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆