我正在尝试从 Express 后端获取图像并将其显示在 React js 前端中。我怎样才能完美地实现这一目标?
我尝试获取保存在名为“Backup”的后端文件夹中的图像,并将它们在 React js 前端显示给用户。我已经使用 axios 尝试过此操作,但仍然得到无效图像而不是正确的图像。
以下是我在前端的获取请求。
fetchImages = () => {
const imageName = 'garande.png'
const url = `http://localhost:5000/fetchImage/${imageName}`
axios.get(url, {responseType: 'blob'})
.then(res => {
return(
<img src={res.data} alt="trial" />
)
}
}
Run Code Online (Sandbox Code Playgroud)
这就是我在后端的 server.js 文件中的内容
app.get('/fetchImage/:file(*)', (req, res) => {
let file = req.params.file;
let fileLocation = path.join('../Backup/images/', file);
//res.send({image: fileLocation});
res.sendFile(`${fileLocation}`)
})
Run Code Online (Sandbox Code Playgroud)
我希望图像显示在用户页面中。谢谢。