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

React图书项目图片加载出现404错误,请求排查原因

React项目图书图片加载404问题排查

我是React新手,正在开发一个图书项目,但应用无法加载图书图片,浏览器提示“Failed to load resource: the server responded with a status of 404 (Not Found)”错误。以下是相关信息:

项目目录结构

项目目录结构

App.jsx代码

import "./App.css";

import data from "./data";

export default function BookList() {
  return (
    <section className="book-list">
      {data.map((book) => {
        const { id, title, author, imageLink } = book;
        return <Book book={book} />;
      })}
    </section>
  );
}

function Book(props) {
  const { id, title, author, imageLink } = props.book;
  console.log(id, title, author, imageLink);
  return (
    <article className="book">
      <h4>{id}</h4>
      <img src={imageLink} alt="" />
      <h1>{title}</h1>
      <h4>{author}</h4>
    </article>
  );
}

data.js数据格式示例

export default [
  {
    author: "Chinua Achebe",
    country: "Nigeria",
    imageLink: "./assets/images/things-fall-apart.jpg",
    language: "English",
    link: "https://en.wikipedia.org/wiki/Things_Fall_Apart\n",
    pages: 209,
    title: "Things Fall Apart",
    year: 1958,
    id: 0,
  },
  {
    author: "Hans Christian Andersen",
    country: "Denmark",
    imageLink: "./assets/images/fairy-tales.jpg",
    language: "Danish",
    link: "https://en.wikipedia.org/wiki/Fairy_Tales_Told_for_Children._First_Collection.\n",
    pages: 784,
    title: "Fairy tales",
    year: 1836,
    id: 1,
  },
  {
    author: "Dante Alighieri",
    country: "Italy",
    imageLink: "./assets/images/the-divine-comedy.jpg",
    language: "Italian",
    link: "https://en.wikipedia.org/wiki/Divine_Comedy\n",
    pages: 928,
    title: "The Divine Comedy",
    year: 1315,
    id: 2,
  }
];

浏览器错误信息

浏览器错误信息

浏览器预览效果

浏览器预览无内容


问题原因及解决办法

  1. 静态资源路径配置问题
    React开发服务器默认仅提供public目录下的静态资源访问。如果你的assets文件夹不在public目录内,浏览器请求./assets/images/xxx.jpg时,服务器无法找到对应文件,就会返回404。

    • 解决步骤:把assets文件夹直接移动到项目根目录的public文件夹下,这样浏览器请求的路径就能正确映射到public/assets/下的资源。
  2. 资源导入方式问题(可选)
    如果不想移动assets目录,也可以通过ES模块导入图片资源:

    • 修改data.js,逐个导入图片:
      import thingsFallApart from './assets/images/things-fall-apart.jpg';
      import fairyTales from './assets/images/fairy-tales.jpg';
      import divineComedy from './assets/images/the-divine-comedy.jpg';
      
      export default [
        {
          // ...其他字段
          imageLink: thingsFallApart,
          // ...
        },
        // 其他书籍同理
      ];
      

    这种方式下Webpack会自动处理图片资源,生成正确的访问路径。

  3. 额外注意事项

    • 检查图片文件名和路径的大小写:Linux/macOS系统对文件名大小写敏感,如果实际文件名与代码中写的大小写不一致,也会导致404。
    • 给map渲染的组件添加key属性:在BookList组件的map回调里,返回<Book book={book} key={book.id} />,避免React的列表渲染警告。

内容的提问来源于stack exchange,提问作者Asir Shahriar Roudra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 17:12:46