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

如何在React组件中渲染数据库存储的图片?

问题:React组件无法渲染API服务器上的图片

我有一个React的Game组件,API服务运行在5000端口,图片存储在API服务器的public/uploads目录下,但组件里的图片始终无法渲染。

Game组件代码

import React from 'react'
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import '../../styles/components/Games/Game.css'


function Game({game}) {

  const { name, description, employees, hours, photo } = game;

  const formatDateTime = (dateTimeString) => {
  const dateTime = new Date(dateTimeString);
  const day = dateTime.getDate();
  const month = dateTime.getMonth() + 1;
  const year = dateTime.getFullYear();
  const hours = String(dateTime.getHours()).padStart(2, '0');
  const minutes = String(dateTime.getMinutes()).padStart(2, '0');

  return `${day}/${month}/${year} ${hours}:${minutes}`;
  };

  const openingTimes = hours.map((time) => formatDateTime(time.opening));
  const closingTimes = hours.map((time) => formatDateTime(time.closing));

  return (
    <div className='game_card'>
        <div className="game_heading">
            <div className="image_container">
                <img src={`http://localhost:5000/public/uploads/${photo}`} alt="no photo" />
            </div>
            <h1>{name}</h1>
        </div>
        <div className="game_content">
            <p>Game Description</p>
            <div className="game_hours">
            {`${openingTimes} ${closingTimes}`}
            </div>
        </div>
        <button><ExpandMoreIcon/></button>
        <div className="employees">
            <p>Employees</p>
        </div>
    </div>
  )
}

export default Game

游戏对象示例

{
    "_id": "648a5a8beccdb1f0cc27e026",
    "name": "Fantasy World",
    "description": "Immerse yourself in a realm of imagination and wonder with captivating rides and shows.",
    "photo": "photo_648a5a8beccdb1f0cc27e026.jpg",
    "employees": [
        "5d713995b721c3bb38c1f5d8",
        "5d713995b721c3bb38c1f5d9"
    ],
    "hours": [
        {
            "opening": "2023-06-07T12:00:00.000Z",
            "closing": "2023-06-07T22:00:00.000Z",
            "_id": "648a5a8beccdb1f0cc27e027"
        },
        {
            "opening": "2023-06-08T14:00:00.000Z",
            "closing": "2023-06-09T00:00:00.000Z",
            "_id": "648a5a8beccdb1f0cc27e028"
        }
    ],
    "available": true,
    "createdAt": "2023-06-07T16:00:00.000Z",
    "__v": 0
}

已排查情况

  • API服务器的public/uploads/photo_648a5a8beccdb1f0cc27e026.jpg文件确实存在
  • 将img的alt属性设为{photo}时,能正常显示文件名,说明photo变量取值正确

解决方案

1. 修正静态资源访问路径

如果API用Express搭建,配置静态文件中间件后,public目录会成为根路径,不需要在URL中包含public。

首先确保Express服务器已配置静态资源托管:

const express = require('express');
const app = express();

// 托管public目录下的静态资源
app.use(express.static('public'));

然后修改组件中img的src路径:

<img src={`http://localhost:5000/uploads/${photo}`} alt={photo} />

2. 解决跨域问题

若React应用运行在其他端口(如3000),需在API服务器配置CORS允许跨域访问:

const cors = require('cors');
// 允许所有来源跨域(开发环境可用)
app.use(cors());

// 或限制特定来源(生产环境推荐)
// app.use(cors({
//   origin: 'http://localhost:3000',
//   credentials: true
// }));

3. 验证图片可直接访问

在浏览器地址栏输入http://localhost:5000/uploads/photo_648a5a8beccdb1f0cc27e026.jpg,检查是否能正常加载图片:

  • 若无法加载,检查文件路径大小写、服务器文件读取权限、服务器端口是否正确
  • 若能加载,说明组件路径拼接有误,可在组件中打印路径排查:
console.log(`http://localhost:5000/uploads/${photo}`);

内容的提问来源于stack exchange,提问作者tukitooo1998

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 01:17:43