【问题标题】:piping incoming http get request to outgoing write request on nodejs not working as expected将传入的http get请求传递给nodejs上的传出写入请求未按预期工作
【发布时间】:2020-07-21 16:43:51
【问题描述】:

我正在尝试构建一个基本的发布/订阅事件发射器,但我无法理解如何将带有有效负载的传入事件通过管道传输到所有事件的订阅者。这就是我所拥有的:

app.post("/events", (req, res) => {
  const { type } = req.body;
  if (!type) {
    res.status(404).send(`no event found`);
    return;
  }
  if (!eventTypeToUrls[type]) {
    res.status(404).send(`no event ${type} subscribed to`);
    return;
  }
  let count = 0;
  const urls = eventTypeToUrls[type];
  urls.forEach((url) => {
    console.log("sending payload to >>", url);
    const writeStream = http.request(
      url + "/events",
      { method: "post" },
      () => {
        count += 1;
        if (count === urls.length) {
          res.status(201).send("ok");
        }
      }
    );
    writeStream.on("error", (e) => res.status(401).send(e));
    req.pipe(writeStream);
  });
});

我看到我可能在非管道设置中需要使用序列化的有效负载调用 res.write,但由于我是从可读流管道到可写流,我不确定具体如何改变。我想我也不需要打电话给res.end。谢谢。

【问题讨论】:

  • 澄清一下 - 您想发送多个 http 请求(使用传递给 POST /events 的请求负载)?

标签: node.js


【解决方案1】:

问题是可读的req-stream 将已经被消耗,一旦请求处理程序回调被命中,因此你不能将它传送到可写的流。

但是,如果您只想向所有订阅者 url 发送 http-requests,您可以使用 Promise.all 等待请求的非顺序处理,并在所有承诺都履行后简单地执行 res.status(..).send(..)。像这样的东西(我在这里使用 superagent 作为 http-request 库):

app.post('/events', async (req, res) => {
  // ...
  try {
    await Promise.all(urls.map(url => {
      return superagent
        .post(url + '/events')
        .send(req.body);
    }));
    res.status(201).send("ok");
  } catch (err) {
    res.status(500).end('something went wrong ...');
  }
});

【讨论】:

    猜你喜欢
    • 2018-04-24
    • 1970-01-01
    • 2018-05-14
    • 2015-01-20
    • 2018-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多