在node.js中输出之前更改响应正文

Change response body before outputting in node.js

本文关键字:响应 正文 node js 输出      更新时间:2023-09-26

我是Node.js的新手。我正在尝试构建一个小型服务器,作为对开放数据服务POST调用的代理,然后做一些事情,绑定到表示层,最后输出到浏览器。

这是代码:

dispatcher.onGet("/metro", function(req, res) {
  var r = request({body: '<?xml version="1.0" encoding="ISO-8859-1" ?><poirequest><poi_id>87087</poi_id><lng>0</lng></poirequest>'}, function (error, response, body) { 
if (!error && response.statusCode == 200) {
   console.log('Public transformation public API called');
  }
}).pipe(res);
res.on('finish', function() {
  console.log('Request completed;');
});
}); 
http.createServer(function (req, res) {
  dispatcher.dispatch(req, res);
}).listen(1337, '0.0.0.0');
console.log('Server is listening');

调度员是我在mpm上发现的最简单的:https://npmjs.org/package/httpdispatcher问题是:在输出到输出管道之前,我如何更改(基本上是html代码剥离)响应主体?

您可以使用类似concat流的东西来累积所有流数据,然后将其传递给回调,在将其返回到浏览器之前,您可以在回调中对其进行操作。

var concat = require('concat-stream');
dispatcher.onGet("/metro", function(req, res) {
  write = concat(function(completeResponse) {
    // here is where you can modify the resulting response before passing it back to the client.
    var finalResponse = modifyResponse(completeResponse);
    res.end(finalResponse);
  });
  request('http://someservice').pipe(write);
}); 
http.createServer(dispatcher.dispatch).listen(1337, '0.0.0.0');
console.log('Server is listening');