English 中文(简体)
快速返回
原标题:Return fetch stream from Fastify

我的“快车”服务器需要向另一个服务机构提出替代要求,当我收到答复时,我正试图把双向反馈给客户,但答复是空的。 这里,我利用一个公开的公益物创建的榜样;斯塔尔·瓦尔斯·安森。

const fastify = require("fastify")({ logger: true });

// return JSON from SWAPI - works!
fastify.get("/api/json", async (request, reply) => {
  const response = await fetch("https://swapi.dev/api/people/1/");
  const json = await response.json();
  return reply.send(json);
});

// return stream from SWAPI - doesn t work
// response is an empty object: {}
fastify.get("/api/stream", async (request, reply) => {
  const response = await fetch("https://swapi.dev/api/people/1/");
  return reply.send(response.body);
});

fastify.listen({ port: 3000 }, (err) => {
  if (err) {
    fastify.log.error(err);
    process.exit(1);
  }
});

Above is the entire server file, but you can also clone my GitHub repo if you want to:
https://github.com/TJBlackman/fastify-stream-test

Thanks in advanced for the help!

问题回答

快速维护者实际上在吉安布回答这个问题! 感谢@uzlopak

 use strict 
const { pipeline } = require( node:stream )

const fastify = require(".")({ logger: true });

fastify.get("/api/stream", async (request, reply) => {
  const response = await fetch("https://swapi.dev/api/people/1/");
  pipeline(
    response.body,
    reply.raw,
    (err) => err && fastify.log.error
  );
  return reply;
});

fastify.listen({ port: 3000 }, (err) => {
  if (err) {
    fastify.log.error(err);
    process.exit(1);
  }
});

I guess, fetch returns a WHATWG Stream, which is not providing a pipe method, thus not being streamed when using reply.send.

On Github:





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签