我的 Fastify 服务器需要将请求代理到另一个服务,当我收到响应时,我试图将流传递回客户端,但响应为空。这是我使用流行的开放 API 创建的示例;星球大战 API。
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);
}
});
上面是整个服务器文件,但如果您愿意,您也可以克隆我的 GitHub 存储库:
https://github.com/TJBlackman/fastify-stream-test
提前感谢您的帮助!
Fastify 维护者实际上在 Github 上回答了这个问题!感谢@uzlopak
'use strict'
const { pipeline } = require('node:stream')
const fastify = require(".")({ logger: true });
// return stream from SWAPI - doesn't work
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);
}
});
我猜,fetch 返回一个 WHATWG Stream,它没有提供管道方法,因此在使用reply.send时不会被流式传输。