如何从 express api 中获取多个图像到 React 应用程序中?
How to fetch mutiple images from express api's into react application?
我正在使用 mern stack 来编写应用程序。我使用带有 express 的 multer 包进行文件上传,并在 node.js 应用程序的目录中上传图像。现在我想从那个目录中获取图像。我怎样才能做到这一点?我找到
res.sendFile()
但有些情况下我需要一次从服务器获取多个文件。我还发现只是从 api 发送路径来做出反应,并从一个文件夹提供服务到我认为不安全的反应中?我该怎么做?
你应该将后端与前端解耦,这意味着,将 express 部分与 React 部分分开并使其变得简单 API,express 也可以作为静态文件提供服务(搜索 google用于静态文件服务),然后从您的 React 应用程序调用 API。只需给出 React 应用程序图像 URL,例如示例。com/static/image1.png(<img src={"example.com/static/image1.png"} />
)
我最终使用流来解决我的问题,以下代码片段可能会对遇到类似问题的人派上用场。
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
});
我正在使用 mern stack 来编写应用程序。我使用带有 express 的 multer 包进行文件上传,并在 node.js 应用程序的目录中上传图像。现在我想从那个目录中获取图像。我怎样才能做到这一点?我找到
res.sendFile()
但有些情况下我需要一次从服务器获取多个文件。我还发现只是从 api 发送路径来做出反应,并从一个文件夹提供服务到我认为不安全的反应中?我该怎么做?
你应该将后端与前端解耦,这意味着,将 express 部分与 React 部分分开并使其变得简单 API,express 也可以作为静态文件提供服务(搜索 google用于静态文件服务),然后从您的 React 应用程序调用 API。只需给出 React 应用程序图像 URL,例如示例。com/static/image1.png(<img src={"example.com/static/image1.png"} />
)
我最终使用流来解决我的问题,以下代码片段可能会对遇到类似问题的人派上用场。
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
});