Home > Software design >  Images that worked locally are broken on NodeJS Heroku App
Images that worked locally are broken on NodeJS Heroku App

Time:06-24

I am new to using Heroku and finding that a specific set of images that worked fine locally show broken links on my deployed app. The console error is "Failed to load resource: the server responded with a status of 404 (Not Found)"

The app is a vanilla Js app with Immutable JS and a Node Express server that consumes data from the Nasa Mars Rover api.

My app on Heroku

My server makes a Get request on click and fetches data and an array of images for 3 Mars Rovers. As the Nasa api didn't include images of the actual rovers themselves, just the images taken by the rover, I found images for each one, stored in my local assets folder and displayed through the api calls like so-

<img src='https://mars-rover-dashboard-app.herokuapp.com/public/assets/images/${
    roverData.rover.get("name")   ".png"}' alt='rover image' class='sidebar__main-rover-img'>

I've researched the problem, and thought it could be because it refers to a path that only exists locally, and not on the Heroku app itself. I added in the url of my Heroku app, and it still doesn't work. Not really sure what else to try?

CodePudding user response:

I am not exactly sure what your problem is but below solution helped me serve images on Heroku. Creating a route for serving images was easier and better when it comes to consuming it from js frontends.

Route for serving images

app.get('/images/:id', jsonParser, (req, res) => {
  const id = req.params.id

  res.sendFile(id, { root: './images' })
})

Put the images folder to where your app.js file is and in your frontend give source like this.

<img src="/images/rovername.png" />

This will create a get request to your /images route with the name of the image like

https://mars-rover-dashboard-app.herokuapp.com/images/rovername.png.

CodePudding user response:

In the end I just wrote logic to return images with absolute paths from the Nasa website. Maybe not the most elegant solution, but a quick fix to get it working for now. In my research i discovered setting up S3 buckets on Amazon Web Services, this is something i will look into for future amends to this app.

  • Related