'Can't show image from database in React.js

I have a problem with this react.js. I can't show my image from the database. Here is my code from product.js

import { useEffect, useState } from "react";

import Card from "../UI/Card";
import MealItem from "./MealItem/MealItem";
import classes from "./AvailableMeals.module.css";

const AvailableMeals = () => {
  const [meals, setMeals] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [httpError, setHttpError] = useState();

  useEffect(() => {
    const fetchMeals = async () => {
      const response = await fetch("http://localhost:8000/product");

      if (!response.ok) {
        throw new Error("Something went wrong!");
      }

      const responseData = await response.json();

      const loadedMeals = [];

      for (const key in responseData) {
        loadedMeals.push({
          id: key,
          name: responseData[key].name,
          description: responseData[key].description,
          price: responseData[key].price,
        });
      }

      setMeals(loadedMeals);
      setIsLoading(false);
    };

    fetchMeals().catch((error) => {
      setIsLoading(false);
      setHttpError(error.message);
    });
  }, []);

  if (isLoading) {
    return (
      <section className={classes.MealsLoading}>
        <p>Loading...</p>
      </section>
    );
  }

  if (httpError) {
    return (
      <section className={classes.MealsError}>
        <p>{httpError}</p>
      </section>
    );
  }

  const mealsList = meals.map((item, index) => (
    <MealItem
      key={item.id}
      id={item.id}
      name={item.name}
      description={item.description}
      price={item.price}
      image={
        <div style={{ width: 360, height: 360, float: "center" }}>
          {" "}
          <img
            style={{ width: "100%", height: "100%" }}
            src={"http://localhost:8000/images/" + item.image}
            alt="Gambar Sesuatu"
          />
        </div>
      }
    />
  ));

  return (
    <section className={classes.meals}>
      <Card>
        <ul>{mealsList}</ul>
      </Card>
    </section>
  );
};

export default AvailableMeals;

Here is my back-end using Node.js:

var http = require("http");
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var mysql = require("mysql");
var multer = require("multer");
const { Console } = require("console");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST, OPTIONS, PUT, PATCH, DELETE"
  );
  if (req.method === "OPTIONS") {
    res.setHeader(
      "Access-Control-Allow-Headers",
      "Origin, X-Requested-With, Content-Type, Accept, Authorization"
    );
    return res.status(200).json({});
  }
  next();
});

app.use("/images", express.static("./images"));

var mysql = require("mysql");
var conn = mysql.createConnection({
  host: "localhost", //nama host database mysql
  user: "root", //user mysql
  password: "", //password mysql
  database: "DatabaseRamen",
});

app.get("/product", (req, res) => {
  var query = "SELECT * FROM product";
  conn.query(query, (err, rows) => {
    res.json(rows);
    console.log(query);
  });
});
var upload = multer({ storage: storageFile }); //buat object upload
app.post("/save-product", upload.single("fileImage"), (req, res) => {
  var product = {
    name: req.body.name,
    description: req.body.description,
    image: req.file.filename,
    price: req.body.price,
  };
  conn.query("INSERT INTO product SET ?", product, (err, result) => {
    res.json(result);
  });
});
app.delete("/product/:id", (req, res) => {


http.createServer(app).listen(8000, () => {
  console.log("Server is running on port 8000");
});

Here is the output for the product:

enter image description here

As you can see I already fetch it and it shows the product but not the image and when I inspect the element. It shows localhost:8000/images/undefined. I don't know what's wrong with the code.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source