0

I am making a sample project e-commerce site wherein I encountered a problem when fetching data from my backend. All other data such as price, rating, etc. are being fetched to the frontend but just the images are not being fetched specifically. I have checked for errors but there is none, only console errors in chrome which implies the images not being found. I have also checked for file extensions but everything is alright. Like I said, other data are being fetched but the images are not.

data.js from backend

const data = {
    products:[
        {
            _id: '1',
            name: 'ADLV Ice Cream Shirt',
            category: 'Shirts',
            image: "/images/adlv ice cream shirt.jpg",
            price: 130,
            countInStock: 0,
            brand: 'ADLV',
            rating: 2.5,
            numReview: 5,
            description: 'high quality oversized fit shirt'
        },
        {
            _id: '2',
            name: 'ADLV Twice Shirt',
            category: 'Shirts',
            image: "/images/adlv twice shirt.png",
            price: 180,
            countInStock: 12,
            brand: 'ADLV',
            rating: 5,
            numReview: 10,
            description: 'high quality oversized fit shirt'
        },
        {
            _id: '3',
            name: 'ADLV Donut Shirt',
            category: 'Shirts',
            image: "/images/adlv donut shirt.jpg",
            price: 150,
            countInStock: 11,
            brand: 'ADLV',
            rating: 4,
            numReview: 15,
            description: 'high quality oversized fit shirt'
        },
        {
            _id: '4',
            name: 'ADLV Skater Shirt',
            category: 'Shirts',
            image: "/images/adlv skater shirt.jpg",
            price: 140,
            countInStock: 13,
            brand: 'ADLV',
            rating: 3.5,
            numReview: 20,
            description: 'high quality oversized fit shirt'
        },
        {
            _id: '5',
            name: 'ADLV Candy Shirt',
            category: 'Shirts',
            image: "/images/adlv candy shirt.jpg",
            price: 160,
            countInStock: 10,
            brand: 'ADLV',
            rating: 3,
            numReview: 25,
            description: 'high quality oversized fit shirt'
        },
        {
            _id: '6',
            name: 'ADLV Bunny Shirt',
            category: 'Shirts',
            image: "/images/adlv bunny shirt.jpg",
            price: 170,
            countInStock: 14,
            brand: 'ADLV',
            rating: 4.5,
            numReview: 30,
            description: 'high quality oversized fit shirt'
        },
    ]
}
export default data;

server.js from backend

import express from 'express';
import data from './data.js';
const app = express();

app.get('/api/products', (req, res)=>{
    res.send(data.products)
})
app.get('/', (req, res)=>{
    res.send('Server is ready');
});
const port = process.env.PORT || 3000;
app.listen(port, ()=>{
    console.log(`serve at http://localhost:${port}`);
});

HomeScreen.js

import React, {useEffect, useState} from 'react';
import axios from 'axios';
import Product from '../components/Product';
import LoadingBox from '../components/LoadingBox';
import MessageBox from '../components/MessageBox';

export default function HomeScreen(){
    const [products, setProducts] = useState([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(false);
    useEffect(()=>{
        const fetchData= async()=>{
            try{
                setLoading(true);
                const {data} = await axios.get('./api/products');
                setLoading(false);
                setProducts(data);
            }catch(err){
                setError(err.message);
                setLoading(false);
            }
            
        };
        fetchData();
    },[])
    return(
        <div>
            {loading ? (<LoadingBox></LoadingBox>)
            : error ? (<MessageBox variant = "danger">{error}</MessageBox>)
            : (<div className="row center">
              {
                products.map(product =>(
                <Product key={product._id} product={product}></Product>))
              }
            </div>)
            }
            
        </div>
    )
}

package.json on frontend

{
  "name": "frontend",
  "proxy": "http://127.0.0.1:3000",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.11.8",
    "@testing-library/react": "^11.2.2",
    "@testing-library/user-event": "^12.6.0",
    "axios": "^0.21.1",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.1",
    "web-vitals": "^0.2.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

package.json on backend

{
  "name": "e-commerce",
  "type": "module",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "nodemon --watch backend --exec node --experimental-modules backend/server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.7"
  }
}

Product.js

import React from 'react'
import Rating from './Rating'
export default function Product(props){
    const {product} = props
    return(
        <div key={product._id} className="card">
                <a href={`/product/${product._id}`}>
                    <img className="medium" src={product.image} alt={product.name}/>
                </a>
                <div className="card-body">
                    <a href={`/product/${product._id}`}><h2>{product.name}</h2></a>
                    <Rating
                    rating = {product.rating}
                    numReview = {product.numReview}></Rating>
                    <div className="price">${product.price}</div>
                </div>
            </div>
    )
}

images sample

sample1

sample2

sample3

sample4

network1

  • Are you saying specifically the image field/property isn't coming through in the response data? Or it is and you are trying to later render this data and the images aren't fetched/rendered? Can you also include the `Product` component code in your question? – Drew Reese Jan 11 '21 at 03:56
  • yes just the images from my files are not being fetched properly from the backend all I see is the alt name for the images – James Craig Jan 11 '21 at 03:59
  • You should be able to examine the network tab in the browser's dev tools and see how these image requests are resolved. Can you include the code that is requesting/loading the images? – Drew Reese Jan 11 '21 at 04:01
  • please see my edited post. thanks in advance! i just do not get why specifically the images are not being fetched but other data are being fetched fine that is why I am stuck at this part – James Craig Jan 11 '21 at 04:07
  • So with an image source like "/images/adlv ice cream shirt.jpg" are they available in the public directory? Perhaps remove all the spaces in the name since spaces aren't allowed in URLs. See: https://stackoverflow.com/a/4172592/8690857 – Drew Reese Jan 11 '21 at 04:13
  • damn bro u saved my day i didn't know that! thank you very much for the help bro and for the new information that u gave me. thank you very much for helping me! u da best man! – James Craig Jan 11 '21 at 04:27

0 Answers0