【问题标题】:Correct picture path正确的图片路径
【发布时间】:2021-10-24 01:35:12
【问题描述】:

我有这个site

(在 Heroku 中部署的 Gatsby 和 Strapi API)。我的问题是我找不到合适的路径来渲染图片。

这里是API,这里是repo

我关于图片渲染的代码:

  .map(band => (
        <article className="bands" key={band.id}>
          <h2>{band.band_name}</h2>
          <img
            src={band.band_img.name}
            alt={band.band_name}
          />
          <p>{band.band_desc}</p>

我已经将 src={band.band_img.name} 替换为许多内容,例如:

band.band_img.formats.thumbnail.url

band.band_img.网址

如此等等都无济于事。

我的一个朋友告诉我创建 .env 文件

uploads_path: /uploads/ (.env.production)

uploads_path: 上传/ (.env)

我做了,什么也没做。

console.log(band.band_img)的图片

请问有什么建议吗?提前谢谢你。

【问题讨论】:

  • console.log(band.band_img) 返回什么?您可以在 obj 中查找 url
  • 看来问题出在 Heroku 上。谢谢。
  • lebraojohns.netlify.app 现在显示图像。根据答案总结实现该目标的步骤:a)在/通过 Heroku 中部署 Strapi API:docs,或者如果您更喜欢video; b) Heroku 在本地上传时确实会破坏/删除图像,因此我将 Cloudinary 设置为服务它们并按照docs 将其连接到 Strapi; c) 反对

标签: reactjs heroku strapi


【解决方案1】:

您的问题是图片没有上传。如果您查看以下图像路径,它们将不会显示(到目前为止您正在尝试的内容):

我已尝试查看多条路径,但没有一条适合我。

您将看不到任何图像,因此您的代码无法在 band.band_img.name 显示任何内容,根据您的 API 应该是:

band_img: {
  id: 7,
  name: "badreligion.jpeg",
  alternativeText: "",
  caption: "",
  width: 315,
  height: 160,
  formats: {
    thumbnail: {
      ext: ".jpeg",
      url: "/uploads/thumbnail_badreligion_7007c2c028.jpeg",
      hash: "thumbnail_badreligion_7007c2c028",
      mime: "image/jpeg",
      name: "thumbnail_badreligion.jpeg",
      path: null,
      size: 9.63,
      width: 245,
      height: 124
   }
}

P.S:我喜欢 Bad Religion 和所有乐队 ?

修复图片上传/服务器问题后,您的代码看起来不错,代码应该可以单独运行。

除非您在一个组件中使用它们,否则您的代码将永远无法访问您存储在 /src/assets 下的图像(转译到公用文件夹)。

根据您的规格,您可以通过在/static folder 下添加您的图像来绕过它,将它们克隆到公共图像中。

【讨论】:

  • 感谢您的解释。我都明白了。 P.S.:一旦我解决了这个问题,就有超过一百个朋克乐队要添加。
【解决方案2】:

这是您的服务器的问题,例如以下应该可以工作:

const getBandImg = (band) => band.band_img?.formats?.url;

并在任何你想获取 img url 的地方使用它:

  .map(band => (
        <article className="bands" key={band.id}>
          <h2>{band.band_name}</h2>
          <img
            src={getBandImg(band)}
            alt={band.band_name}
          />
          <p>{band.band_desc}</p>

您已经尝试过使用 band.band_img.formats.thumbnail.url,但在查看您的网站后,我注意到图像在 API 或前端都无法访问,例如:

https://john-strapi.herokuapp.com/uploads/dri_6a22b5e947.jpeg 不返回图片

https://lebraojohns.netlify.app/uploads/dri_6a22b5e947.jpeg 都没有

所以这是你必须在主机中解决的问题,而不是 gatsby 的问题

【讨论】:

  • 谢谢。我会尝试在 Heroku 中找到问题(可能)。
猜你喜欢
  • 2018-03-11
  • 1970-01-01
  • 1970-01-01
  • 2019-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-02
  • 1970-01-01
相关资源
最近更新 更多