React项目中如何正确展示通过Axios请求获取的图片
问题原因及解决方案
1. 修复基础拼写错误
你定义的请求函数名为getimage,但按钮点击事件绑定的是getImage,大小写不匹配会导致点击按钮无响应,首先统一函数命名。
2. 修正图片路径取值逻辑
img标签的src属性只接受图片资源的访问地址字符串,不能直接传入文件对象:
- 返回的file数组每个元素是上传文件的元信息,其中
destination字段对应后端静态资源托管目录,filename(multer上传默认生成字段,可自行打印完整file对象确认)是文件存在服务器上的实际文件名 - 后端静态资源默认托管在
http://localhost:4000/根路径下,./public/是后端本地目录标识,前端访问时要去掉,拼接为http://localhost:4000/newPostData/[filename]
3. 修正后的完整代码
import React, { useState } from "react"; import Axios from "axios"; function MyUploader() { // 多图存储用数组 const [imageList, setImageList] = useState([]); const getImage = () => { Axios.get("http://localhost:4000/getAllPosts").then((res) => { const fileArr = (res && res.data && res.data[0].file) || []; // 拼接完整的图片访问路径 const formattedImageList = fileArr.map(fileItem => { return `http://localhost:4000/newPostData/${fileItem.filename}` }) setImageList(formattedImageList); }); }; return ( <div className="App"> {/* 遍历渲染所有图片 */} {imageList.map((imgSrc, index) => ( <img key={index} src={imgSrc} alt={`product-img-${index}`} style={{width: '200px', margin: '10px'}}/> ))} <button onClick={getImage}>getdata</button> </div> ); }
额外排查项
- 确认后端已开启public目录的静态资源托管,直接在浏览器访问拼接后的图片地址,能正常打开说明路径正确
- 如果React项目和后端接口跨域,可在React项目的package.json中配置
"proxy": "http://localhost:4000",此时拼接路径可简写为/newPostData/${fileItem.filename}
内容的提问来源于stack exchange,提问作者Rizwan Ali
相关产品推荐
相关产品推荐

