Connect或Express中间件来修改response.body
我想有一个中间件function,修改响应正文。
这是一个快递服务器。
就像是:
function modify(req, res, next){ res.on('send', function(){ res.body = res.body + "modified" }); next(); } express.use(modify);
我不明白要听什么事。 任何帮助或文件将不胜感激。
你不需要听任何事件。 只要做到这一点
function modify(req, res, next){ res.body = res.body + "modified"; next(); }
并在use
路由器后use
它。 这种方式毕竟你的路线已经执行,你可以修改身体
我相信OP实际上是想在中间件处理请求后修改响应stream。 查看捆绑的Compress中间件实现,了解如何完成这个过程。 连接猴子补丁的ServerResponse
原型,当writeHead
调用时,但在它完成之前,发出header
事件。
使用Express 4覆盖响应的写入方法似乎适用于我。这允许修改响应的身体,即使它是一个stream。
app.use(function (req, res, next) { var write = res.write; res.write = function (chunk) { if (~res.getHeader('Content-Type').indexOf('text/html')) { chunk instanceof Buffer && (chunk = chunk.toString()); chunk = chunk.replace(/(<\/body>)/, "<script>alert('hi')</script>\n\n$1"); res.setHeader('Content-Length', chunk.length); } write.apply(this, arguments); }; next(); });
只要确保在可能正在修改响应的任何其他中间件之前注册这个中间件。
明快是为此而devise的。 它只是更多的中间件而不是事件。 你的例子看起来像
const mung = require('express-mung') module.exports = mung.json(body => body.modifiedBy = 'me');
似乎有一个模块来做这个叫做connect-static-transform
,检查出来:
https://github.com/KenPowers/connect-static-transform
连接中间件,允许在服务之前转换静态文件。
它带有像这样的例子。