如何将 Nodejs 获取响应的响应通过管道传输到快速响应

问题描述 投票:0回答:3

我想将来自nodejs fetch 请求的响应通过管道传输到快速响应,就像使用node-fetch 模块一样

const fetchResponse = awair fetch(myUrl);
fetchResponse.body.pipe(expressResponse);
node.js express fetch node-streams
3个回答
0
投票

非常有趣,我想你可能想这样做

import express from 'express';
import fetch from 'node-fetch';

const app = express();
const PORT = 3000;

app.get('/proxy', async (req, res) => {
  const url = 'https://stackoverflow.com/questions/76958222/how-to-pipe-response-from-nodejs-fetch-response-to-an-express-response'; // Replace with your URL

    const fetchResponse = await fetch(url);
    console.log('Response received' + fetchResponse.body);
    fetchResponse.body.pipe(res);
});

app.listen(PORT, () => {
  console.log(`http://localhost:${PORT}`);
});

然后就可以使用 http://127.0.0.1:3000/proxy 访问该网址


0
投票

已经过去 4 个月了,所以我希望你能找到这个。我相信您正在寻找这个:

const { Readable } = require( "stream" );
/*
 * or maybe you'd prefer
 * 
 * import { Readable } from "stream";
 */

/* Insert code here. */

...

const fetchResponse = await fetch(myUrl); 
Readable.fromWeb( fetchResponse.body ).pipe( expressResponse );

Readable.fromWeb() 将为您提供您正在寻找的 Stream.Readable。

您遇到的“问题”是 Node.js 版本的 fetch 符合标准。从理论上讲,这是一件好事,因为你应该知道你会得到什么。

它将新的 Stream 标准引入 Node.js。您可能已经熟悉 Streams 库的 Readable 和 FS.ReadStream。它可能感觉像是一个诱饵和开关,但在从标准的 node-fetch 转向完全兼容的 fetch 时,您已经尴尬地引入了同样符合标准的 ReadableStream。这个新的流实现没有您习惯的 pipeline() 方法,而是具有 pipelineThrough() 和 pipelineTo()。

标准参考:


-1
投票

如果您决定使用 axios 而不是本机 fetch,您仍然可以通过使用流功能直接流式传输响应来实现此目的。

以下是使用 axios 的方法:

首先安装axios:

npm install axios

使用 axios 发出请求并通过管道传输响应:

const express = require('express');
const axios = require('axios');

const app = express();

app.get('/proxy', async (req, res) => {
    const url = 'YOUR_TARGET_URL_HERE';

    // Axios request with responseType set to 'stream'
    const response = await axios.get(url, { responseType: 'stream' });
    
    // Set the headers from the original response, if needed
    res.set(response.headers);

    // Pipe the Axios response stream directly to the Express response
    response.data.pipe(res);
});

app.listen(3000, () => {
    console.log('Server started on http://localhost:3000');
});

我希望这能给你一个想法。

© www.soinside.com 2019 - 2024. All rights reserved.