javascript 从JSON导入的相对路径图像未加载到Next.js中

ddrv8njm  于 2022-11-20  发布在  Java
关注(0)|答案(2)|浏览(154)

JSON文件数据分数:

{
  "categories": [
    {
      "id": 1,
      "category_slug": "food_supplements",
      "title": "Food Supplements",
      "image": "/../../public/images/foodSupplements.png",
    }
  ]
}

呈现图像的组件数据部分:

{
  Data.categories.map((category, idx) => {
    return (
      <div key={idx} className="header-categories-container">
        <Image className="header-btn-image" src={category.image} alt="btn-img" width="64" height="64"></Image>
        <Link href={`/${category.route}`}>
          <button className="header-category-button">{category.title}</button>
        </Link>
      </div>
    )
  })
}

控制台中出现的错误如下:请求的资源不是有效的图像,无法访问/. .//public/images/foodSupplements.png received text/html;字符集=utf-8
尝试将图像放入不同的源,仍然不起作用。尝试使用src=require(...)导入,仍然是相同的错误。

ymdaylpp

ymdaylpp1#

"试试看"

{
  "categories": [
    {
      "id": 1,
      "category_slug": "food_supplements",
      "title": "Food Supplements",
      "image": "/images/foodSupplements.png",
    }
  ]
}

分析

如果public文件夹中有images文件夹,则在运行时(在浏览器中),您可以直接从公共文件夹中提取资产,即/images/foodSupplements.png = public/images/foodSupplements.png

qvtsj1bj

qvtsj1bj2#

将该文件添加到public文件夹,并将映像路径更改为该文件夹。
"image": "/foodSupplements.png",应该可以修复此问题

相关问题