You need to enable JavaScript to run this app. React调用API路径渲染图片报Module not found错误如何解决
优惠活动
大模型
产品
解决方案
定价
更多

React调用API路径渲染图片报Module not found错误如何解决

问题根因

require 是 webpack 等打包工具在编译阶段执行的静态资源引入方法,仅能处理项目内已存在的静态文件路径。你拼接的 /api/v1/xxx 是运行时才会生成的后端接口动态路径,打包阶段这个路径对应的文件在本地项目里不存在,自然会触发模块未找到的报错。

解决方法

后端接口返回的可直接访问的商品图片路径,不需要用 require 包裹,直接把拼接后的路径赋值给 src 即可:

// carousel items 修改后
const carouselItems = [
  {
    // 去掉require,直接赋值拼接后的接口路径
    src: `/api/v1/ProductFile/${encodeURIComponent(
                      data.data.ID
                    )}/Product/${encodeURIComponent(
                      data.data.ProductImages[0]
                    )}`,
    altText: "Somewhere",
    caption: "Somewhere",
  },
  // 剩余本地静态资源的require无需改动
  {
    src: require("assets/img/megan-product-2.jpg"),
    altText: "Somewhere else",
    caption: "Somewhere else",
  },
  {
    src: require("assets/img/megan-product-3.jpg"),
    altText: "Here it is",
    caption: "Here it is",
  },
  {
    src: require("assets/img/megan-product-4.jpg"),
    altText: "Here it is",
    caption: "Here it is",
  },
];

额外注意点

  • 如果你的接口路径不是和前端同域名,需要拼接完整的服务端域名前缀,比如 https://你的后端域名/api/v1/xxx
  • 如果商品图片接口需要鉴权(比如需要携带token才能访问),不能直接赋值路径给img src,需要先通过fetch/axios请求接口拿到Blob数据,再用URL.createObjectURL(blob)生成临时路径赋值给src

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 06:54:02