Question:
How can I serve an image using Nodejs Reactjs

Problem

I want to display images in the front end. Images were saved in the PostgreSQL database with a static path. I'm trying to set up an Express server to serve these images, but it's not working.


Here code:


productCard


import React, { useEffect, useState } from "react";

import axios from "../config/axios";

import ProductItem from "./ProductItem";


function ProductCard() {

  const [products, setProducts] = useState([]);


  useEffect(() => {

    const getData = async () => {

      try {

        const response = await axios.get("/api/product");

        setProducts(response.data);

      } catch (error) {

        console.error("Error fetching product data:", error);

      }

    };


    getData();

  }, []);


  return (

    <>

      {products?.map((el) => {

        return (

          <ProductItem

            key={el?.id}

            src={el?.img}

            name={el?.name}

            description={el?.description}

            price={el?.price}

            file={el?.file}

          />

        );

      })}

    </>

  );

}


export default ProductCard;


productItem


import React from "react";

import { Card } from "antd";

const { Meta } = Card;


function ProductItem({ name, description, price, file }) {

  console.log(file);

  return (

    <>

      <Card

        hoverable

        style={{ width: 240 }}

        cover={<img alt="example" src={file} />}

      >

        <Meta title={name} description={description} />

        <p className="mt-2 flex justify-end">{price}</p>

      </Card>

    </>

  );

}


export default ProductItem;


This is what I got when I log file:


1696953634614-281617729calendar1.jpg

1696953636442-290084764calendar1.jpg

1696953636442-290084764calendar1.jpg


server


const express = require("express");

const cors = require("cors");

const morgan = require("morgan");

const bodyParse = require("body-parser");


const authRoute = require("./routes/authRoute");

const productRoute = require("./routes/productRoute");

const userRoute = require("./routes/userRoute");

const path = require("path");

const app = express();


app.use(cors());

app.use(morgan("dev"));

app.use(bodyParse.json({ limit: "10mb" }));

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

app.use(express.json());


app.use("/", authRoute);

app.use("/api", productRoute);

app.use("/users", userRoute);


app.use("/assets", express.static(path.join(__dirname, "assets")));


const port = process.env.PORT || 8000;


app.listen(port, () => {

  console.log(`Server is running on port ${port}`);

});


How to fix it? Thank you


Solution

Since you serve your files from “/assets” path, then you need to use the correct path in your ProductItem component

<img alt="example" src={`/assets/${file}`} />


Answered by: >Abdulrahman olalekan

Credit: >StackOverflow


Blog Links: 

>How do I customize controller actions in Laravel Jetstream?

>Run Laravel Project to Active Local Server

>How to show encrypted user id in URL in Laravel?

>How to fix Laravel LiveWire listener?


Nisha Patel

Nisha Patel

Submit
0 Answers