node.jsexpressejsomdbapi

How to change image src in ejs, in case some image that got from OMDb API have src ="N/A"


I use API from OMDb to use movies data to my web site, but some movies they don't have poster data so it send src = "N/A". <img src="<%=movie.Poster%>" alt="movie's poster" width="300px" height="450px">. I use this code in ejs to get images but I want to change image src when it got src="N/A". Can someone help please?

This is my full code:

index.js

import express from "express";
import bodyParser from "body-parser";
import pg from "pg"
import axios from "axios";

const app = express();
const port = 3000;
const API_URL = "https://www.omdbapi.com"
const apikey = "XXXXX"

let defaults = [
  {
    Title: "The Shawshank Redemption",
    Year: "1994",
    imdbID: "tt0111161",
    Type: "movie",
    Poster: "https://m.media-amazon.com/images/M/MV5BNDE3ODcxYzMtY2YzZC00NmNlLWJiNDMtZDViZWM2MzIxZDYwXkEyXkFqcGdeQXVyNjAwNDUxODI@._V1_SX300.jpg"
  },
  {
    Title: "The Godfather",
    Year: "1972",
    imdbID: "tt0068646",
    Type: "movie",
    Poster: "https://m.media-amazon.com/images/M/MV5BM2MyNjYxNmUtYTAwNi00MTYxLWJmNWYtYzZlODY3ZTk3OTFlXkEyXkFqcGdeQXVyNzkwMjQ5NzM@._V1_SX300.jpg"
  },
  {
    Title: "Breaking Bad",
    Year: "2008–2013",
    imdbID: "tt0903747",
    Type: "series",
    Poster: "https://m.media-amazon.com/images/M/MV5BYmQ4YWMxYjUtNjZmYi00MDQ1LWFjMjMtNjA5ZDdiYjdiODU5XkEyXkFqcGdeQXVyMTMzNDExODE5._V1_SX300.jpg"
  }
];

let movies = defaults;


const db = new pg.Client({
    user: "postgres",
    host: "localhost",
    database: "XXXXX",
    password: "XXXX",
    port: XXXX,
  });

db.connect();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));

app.get("/",async(req,res)=>{
  res.render("index.ejs",{Movies:movies});
})

app.post("/",async(req,res)=>{
  movies=[];
  const title = req.body.title
  const type = req.body.type

  try{
    const result = await axios.get(`${API_URL}/?apikey=${apikey}&s=${title}&type=${type}`);
    const data = result.data;
    //console.log(data.Search);
    const response = data.Response; //response

    if(response === "False"){ //for respone "False"
    const error = data.Error; //error
    res.render("index.ejs",{Movies:movies,Error:error});
    movies = defaults; //reset
    }else{ // for respone "True"
      const searchResult = data.Search;
      const first10movie = searchResult; //show only first 10 movies of searching
      //console.log(searchResult);
      movies=first10movie;
      //console.log(movies);
      
      res.redirect("/");
    }


  }catch(err){
console.log(err);
  }
})




app.listen(port, () => {
    console.log(`Server running on port ${port}`);
  });

index.ejs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Review Movie Project</title>
</head>
<body>
    <h1>Review Movie</h1>

    <form action="/" method="post">
        <input name="title" type="text" placeholder="Title" required/>
        <select name="type">
            <option></option>
            <option value="movie">Movie</option>
            <option value="series">Series</option>
        </select>
        <button name="search" type="submit">Search</button>
    </form>

    <%if(Movies && Movies.length > 0){%>
        <%Movies.forEach((movie)=>{%>
            <form action="/review" method="post">
            <div>
            <img src="<%=movie.Poster%>" alt="movie's poster" width="300px" height="450px">
            </div>
        <%})%>
    <%} else { %>
            <h2>Error Response</h2>
            <p><%=Error%></p>
    <%}%>
    <script> var image = document.getElementById("image"); </script>
</body>
</html>

Solution

  • It's JavaScript, so you could use ternary to set src attribute, for example, if movie.Poster value is 'N/A', use some placeholder image, otherwise, use the value:

    <img src="<%=movie.Poster === 'N/A' ? 'https://placehold.co/600x400' : movie.Poster  %>" alt="movie's poster" width="300px" height="450px">
    

    You could set placeholder on the server to make it more efficient and send it to the view:

    const placeholderImg = 'https://placehold.co/600x400';
    
    res.render("index.ejs",{Movies:movies,Error:error, placeholderImg});
    
    <img src="<%=movie.Poster === 'N/A' ? placeholderImg : movie.Poster%>" alt="movie's poster" width="300px" height="450px">