我的 Node/express 应用程序有一个端点,它代理来自内部服务的数据流,该内部服务使用服务器发送的事件。这意味着内部服务将继续永久传输数据,直到连接关闭。
它运行良好,但是当浏览器关闭与我的 Node 应用程序的连接时,与内部服务的管道连接保持打开状态,导致内部服务有很多打开/未使用的连接。
因此,我尝试在 Node 连接关闭时强制关闭管道连接,但似乎不知道如何执行此操作。
代码看起来像这样。使用 request/request
进行管道连接图书馆。
import request from 'request';
app.get('/stream', (req, res) => {
const stream = request.get({
url: 'https://internalservice.acme.com/stream'
})
stream.on('error', console.log);
stream.pipe(res);
// When browser closes...
req.on('close', () => {
// ...close connection to internal service
stream.destroy() // <-- doesn't work
});
});
最佳答案
当您在 Node 中发出请求时,会出现 abort()
方法。它将关闭您的请求流。
req.on('close', () => {
// ...close connection to internal service
stream.abort()
});
关于javascript - 如何关闭 Node 中的无界和管道流请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40875245/