You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

后端存储的图片无法在前端渲染,请求返回404及[object Object]问题排查求助

后端存储的图片无法在前端渲染,请求返回404及[object Object]问题排查求助

各位大佬好,我最近在做一个度假管理的项目,遇到了图片渲染的棘手问题,折腾好一阵没搞定,来求助大家!

问题背景

我的后端用Express + Multer存储度假图片到Images文件夹,文件名格式是{vacationId}_{原始文件名},存储功能是正常的,图片确实能保存到指定目录。前端用React展示度假列表,每个度假项的图片URL是拼接的http://localhost:4000/Images/${props.id}_${props.vacImg},控制台打印出来的文件名完全正确,但图片加载时一直返回404错误;直接在浏览器地址栏输入图片URL,页面显示[object Object],而不是图片或者标准404页面。

相关代码片段

后端server.ts

const server = express();

server.use(cors());
server.use(express.json());
server.use("/api/v1/vacations", router);
server.use("/api/v1/users", userRoutes);

console.log("check if tables exist..");

server.use("*", ErrorHandler); // 注意这个中间件的位置!

server.use(fileUpload);
server.use("/Images", express.static(path.join(__dirname, "Images")));

server.get("/Images/:image", (req, res) => {
  const fileName = req.params.image;
  console.log(__dirname + "/Images" + fileName);
  res.sendFile(__dirname + "/Images/" + fileName);
});

后端FileUpload.ts(Multer配置)

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "Images");
  },
  filename: async (req, file, cb) => {
    const vacationId = req.params.id;
    const originalName = file.originalname.split(".")[0];
    const ext = path.extname(file.originalname);
    const fileName = `${vacationId}_${originalName}${ext}`;
    console.log(fileName);
    console.log(path.join(__dirname, "../Images", fileName));
    cb(null, fileName);
  },
});

const upload = multer({ storage: storage });

后端上传路由

router.post(
  "/:id/upload",
  upload.single("image"),
  (request: Request, response: Response) => {
    response.send("image uploaded successfully");
  }
);

前端SingleVacation组件

interface singleVacationProps {
  id?: number;
  destination: string;
  vacDesc: string;
  vacPrice: number;
  vacImg: string;
}

function SingleVacation(props: singleVacationProps): JSX.Element {
  console.log(`SingleVac: , ${props.id}_${props.vacImg}`);
  return (
    <div className="SingleVacation">
      <Card>
        <CardHeader>{props.destination}</CardHeader>
        <CardMedia
          component="img"
          src={`http://localhost:4000/Images/${props.id}_${props.vacImg}`}
          alt={`${props.destination}`}
        />
        <CardContent>
          <Typography>{props.vacDesc}</Typography>
          <Typography>{props.vacPrice}</Typography>
        </CardContent>
      </Card>
    </div>
  );
}

前端VacationList组件

function VacationList(): JSX.Element {
  const [refresh, setRefresh] = useState(false);
  const dispatch = useDispatch();
  const vacations = useSelector(
    (state: { vacations: { vacations: Vacation[] } }) =>
      state.vacations.vacations
  );
  console.log("Vacations: ", vacations);

  useEffect(() => {
    axios
      .get("http://localhost:4000/api/v1/vacations/list")
      .then((response) => {
        dispatch({
          type: VacationActionType.downloadVacations,
          payload: response.data,
        });
        console.log("Dispatched action:", {
          type: downloadVacations,
          payload: response.data,
        });
      });
  }, [dispatch]);

  return (
    <div className="VacationList">
      <Grid container spacing={2}>
        {vacations.map((item) => (
          <Grid item xs={12} sm={6} md={4}>
            <SingleVacation
              key={item.id}
              id={item.id}
              destination={item.destination}
              vacDesc={item.vacDesc}
              vacImg={item.vacImg}
              vacPrice={item.vacPrice}
            />
          </Grid>
        ))}
      </Grid>
    </div>
  );
}

已排查的点

  • 图片确实存储在后端的Images文件夹,文件名和前端拼接的完全一致
  • 控制台打印的图片文件名是正确的
  • 尝试过在URL里加/backend前缀,没有效果
  • 服务器运行在localhost:4000,端口配置无问题

求助点

为什么直接访问图片URL会返回[object Object]?图片加载404的问题到底出在哪?


备注:内容来源于stack exchange,提问作者DanWi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.22 15:54:42