【问题标题】:Change response body before outputting in node.js在 node.js 中输出之前更改响应正文
【发布时间】:2013-08-09 20:34:38
【问题描述】:

我是 Node.js 的新手。我正在尝试构建一个小型服务器,作为对 opendata 服务的 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 代码剥离)响应正文?

【问题讨论】:

    标签: javascript node.js request pipe


    【解决方案1】:

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

    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');
    

    【讨论】:

    • tnx 分配!对于我的目的来说,这听起来甚至太优雅了,但它确实有效;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-03
    • 2016-06-16
    • 2018-10-10
    相关资源
    最近更新 更多