node.js管道请求到远程服务器并返回res:如何在res结束后将管道断开到res

时间:2017-03-05 17:31:27

标签: node.js express error-handling

我正在使用express并尝试将req传输到远程服务器进行处理,然后通过res将结果传回客户端。它工作得很好,但偶尔我认为res的行为导致write after end结束,导致var onErrorA = function (err) { console.log('error piping to destination:', err); }; var onErrorB = function (err) { console.log('error piping to res:', err); }; var onEndA = function () { console.log('pipe to destination ended'); }; var onEndB = function () { console.log('pipe to res ended'); }; var destination = request(destinationUrl); req.pipe(destination) .on('error', onErrorA) .on('end', onEndA) .pipe(res) .on('error', onErrorB) .on('end', onEndB); 错误。

我的代码目前沿着以下几行(我为了调试目的而过度使用日志记录):

error piping to res: Error: write after end 
pipe to destination ended

我在日志中看到以下内容:

res

如果我对正在发生的事情有所了解,我该如何打破"一旦res结束(超时),管道(停止写入res)?

我已经尝试过以下几点,尝试抓住req.timedout结束时(trueconnect-timeout设置为var destination = request(destinationUrl); var readable = req.pipe(destination); var onData = function (chunk) { if (req.timedout) { // prevent any further writing to res by unpiping it... readable.unpipe(res); } }; // https://nodejs.org/api/stream.html#stream_event_data readable.on('data', onData); readable.pipe(res); TypeError: readable.unpipe is not a function ):

unpipe

但我得到以下错误:

readable

为什么$("#wineNameSelect").on("change", function() { var id = $(this).data("wine-id"); $.ajax({ url: "url_to_wine_details.php", type:"GET", data: {"id", id}, success : function(data) { // parse result in this case the data variable // append them to your ul#results } }); }); 不是"Resource": "arn:aws:s3:::test-bucket" 的函数?

关于如何实现我想要的任何建议?

1 个答案:

答案 0 :(得分:0)

所以我认为我发现了一种有效的方法。不确定它是否是最佳方法,但似乎有效。如果有更好的方法,那么任何其他答案都会很有趣。

我所做的是为res事件附加一个监听器finish,当它触发时,我暂停目的地的可读流,这样就没有其他数据了写到res

var destination = request(destinationUrl);
var readable = req.pipe(destination);
var readableEnded = false;
readable.on('end', function () { readableEnded = true; });
readable.pipe(res);
res.on('finish', function () {
    if (!readableEnded) {
        readable.pause();
        destination.end();
    }
});