Search code examples
javascriptdatabasevue.jsnuxt.jsstrapi

Why is my image request undefined in my Vue.js Nuxt app


I can't figure out why my nuxt app isn't pulling images from my database. I have a list component and separate component for the list items which iterates over project in my project list.

I can pull all other data through like project names, summaries without issue but although I've added images for each project in my Strapi database I can't seem to get the data. I ran a GraphQL query to double check the JSON data which confirms the images are attached to the projects, for example:

 {
    "id": "2",
    "Name": "Kīpuka",
    "image": [
      {
        "url": "/uploads/190217_KIPUKA_Editorial_Mockup_paas_e2e1316f4c.jpeg"
      }
    ]
  },

I am trying to pull the images into my app like this; I'm trying to bind the image source so for every project it shows the respective image.

  <ul :key="project.id">
   <img class="hover-preview" :src="'https://localhost:1337/' + project.image.url" alt="">
   </ul>

The images do not load and the network window shows the request is undefined.

 "Request URL:https://localhost:1337/undefined"

I'm not sure why it can't find the url since it is passed using "project.image.url", I had a look at other questions on Stack Overflow but I couldn't find an answer that seems to fix my issues, any help would be really appreciate as I've hit a wall with this and can't progress.


Solution

  • image in your JSON is an array of images. To get the first image you'd have to use project.image[0].url.

    I'd even add a function to construct that url for you instead of concatenating the strings in your template. For example:

    In your template:

    <ul :key="project.id">
      <img class="hover-preview" :src="buildImageUrl(project.image[0].url)" alt="">
    </ul>
    

    In your methods:

    buildImageUrl(image) {
      if (!image) return "path/to/fallback/image.jpg";
      return `https://localhost:1337/${image}`
    }
    

    EDIT: Updated your codesandbox. It's a lot to recall here. Take a close look at how I handled your JSON and compare it with your initial codesandbox. https://codesandbox.io/s/jovial-montalcini-nmmv3?file=/src/components/ProjectItem.vue

    Keep in mind that the giphy links you chose aren't the actual .gif URLs. Right-click on the gif and copy it's actual address. the URL has to end with .gif.