【问题标题】:Handling "raw data" in Node.js and passing on the data in a Node Express endpoint在 Node.js 中处理“原始数据”并在 Node Express 端点中传递数据
【发布时间】:2019-05-28 08:40:06
【问题描述】:

我正在使用 axios 进行 API 调用以获取文件:

   async function getData() {
    const config = {}; // { responseType: 'stream'};
    const { data } = await axios.get(URL, config);

    console.log(data);
    return data;
   }

当我尝试打印我的 HTTP 请求的结果时,我得到了一堆废话(看起来像某种类型的原始数据) - 快照在这里:

...
�nG��p���1�l�ՓA�zw:/F�  �@LJW>
��⟿_��̠����������=�|�d�s_���A�GԢ������ 
...

我想将此数据(图像或视频文件)传递给到达我的 Node Express 服务器端点的任何人 - 我应该怎么做?我已经阅读了有关使用 Stream 的内容,然后将其通过管道传输到响应中。

   router.get("/file", async(res,res) => {
       const file = await getFile();

       //const stream = fs.createReadStream(file)
       //res.pipe(stream)
   })

我的问题是,我不知道如何处理从 API 返回的数据。我已经尝试将 axios 的 responseType 更改为 stream(default:json) 这给了我一个对象,但也不知道如何处理它。

编辑 - 尝试 1:

 async function getData() {
    const config = { responseType: 'stream'};
    const { data } = await axios.get(URL, config);

    console.log(data);
    return data;
   }

   router.get("/file", async(res,res) => {
       const file = await getFile();

       file.pipe(res);
   })

【问题讨论】:

    标签: javascript node.js express stream axios


    【解决方案1】:

    responseType 是流,axios 解析为一个响应对象,其data 属性是一个流,您可以将其通过管道传递给响应:

     const file = await getFile();
     file.data.pipe(/*to*/ res);
    

    【讨论】:

    • 编辑了我对问题的尝试 - 我尝试管道时出错
    • 确实不一样,那是我的错。道歉
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    • 1970-01-01
    • 2018-12-11
    相关资源
    最近更新 更多