【问题标题】:How to fetch mutiple images from express api's into react application?如何从 express api 获取多个图像到反应应用程序中?
【发布时间】:2020-05-07 19:06:39
【问题描述】:

我正在使用 mern 堆栈来编写应用程序。我使用带有 express 的 multer 包进行文件上传,并在 node.js 应用程序的目录中上传图像。现在我想从该目录中获取图像。我怎样才能做到这一点?我已经找到 res.sendFile() 但在某些情况下,我需要一次从服务器获取多个文件。我还发现只是从 api 发送路径以进行反应,并从文件夹提供到我认为不安全的反应?我该怎么办?

【问题讨论】:

    标签: node.js reactjs mern


    【解决方案1】:

    你应该将后端与前端解耦,也就是说,将 express 部分与 React 部分分开并制作简单的 API,express 也可以将文件作为静态服务(搜索 google 以获取静态文件服务),然后调用 API从你的 React 应用程序。只需提供 React App Image URL,例如 example.com/static/image1.png(<img src={"example.com/static/image1.png"} />)

    【讨论】:

    • 我不知道,但只为动态用户提供公共图像似乎不是一个好主意。
    【解决方案2】:

    我最终使用流来解决我的问题,下面的 sn-p 可能会对遇到类似问题的人派上用场。

    const fs = require('fs')
    const stream = require('stream')
    
    app.get('path',(req, res) => {
      const r = fs.createReadStream('path to file') // or any other way to get a readable stream
      const ps = new stream.PassThrough() // <---- this makes a trick with stream error handling
      stream.pipeline(
       r,
       ps, // <---- this makes a trick with stream error handling
       (err) => {
        if (err) {
          console.log(err) // No such file or any other kind of error
          return res.sendStatus(400); 
        }
      })
      ps.pipe(res) // <---- this makes a trick with stream error handling
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-29
      • 2021-04-09
      • 2016-10-29
      • 2019-10-24
      • 2019-11-27
      • 2022-01-16
      • 2019-11-14
      • 1970-01-01
      相关资源
      最近更新 更多