javascript - 如何关闭 Node 中的无界和管道流请求?

标签 javascript node.js http piping

我的 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/

相关文章:

json - HTTP 原生插件 (IONIC 3)

javascript - 正则表达式错误 : Match is not a function

javascript - 为什么jQuery或诸如getElementById之类的DOM方法找不到元素?

php - 从 PHP 将 Http 状态代码返回给 Apache?

javascript - 使用流将文件保存到 azure 存储不起作用

javascript - Socket.io - 消除抖动?

Ruby:如何将哈希值转换为 HTTP 参数?

javascript - React-Native : ES6 or ES5 classes?

javascript - 使用ajax调用php并返回多个变量?

node.js - 任务 'clean;' 不在使用 Node v0.10.26 的 Windows 中的 gulpfile 中