tri putra
tri putra

Reputation: 5

Error Getting Data from API using FetchData

i am using a react hook : useEffect for getting data from an API and i'm also using .map for rendering an array of product.

after run the npm , there is an error :

xhr.js:178 GET http://localhost:3000/api/products 404 (Not Found)

import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios'

function HomeScreen (props) {

    // menggunakan hooks
    const [products, setProduct] = useState([]);

    // fetchDate from server // sama dengan component did mount
    useEffect( () =>{
        const fetchData = async () => {
            const { data } = await axios.get("/api/products");
            setProduct(data)
        }

        return () => {
        fetchData();
        }
    }, [])
    return(
        <div>
            <ul className="products">
                {
                    products.map( product => 
                        <li key={product.id}>
                            <div className="product"  >
                                <Link to = {`/product/${ product.id }`}>
                                    <img className='product-image' src={ product.image } alt={product.name} />
                                </Link>
                                <div className="product-name">
                                    <Link to = {`/product/${ product.id }`}>{ product.name }</Link> 
                                </div>
                                <div className="product-cat">{ product.brand }</div>
                                <div className="product-price"><b>IDR</b> { product.price }</div>
                                <div className="product-rating">{ product.rating } Stars ( { product.reviews } Reviews )</div>
                            </div>
                        </li>
                    )  
                }
                
            </ul>
        </div>
    )
}

export default HomeScreen

and there is code from server.js

const express = require('express');
const data = require('./database/data')

const app = express();


app.get('/api/products', ( req, res) => {
    res.send(data.Products)
})

const PORT = process.env.PORT || 5001

app.listen(PORT, () => {
    console.log(`Server is Running on http://localhost:${PORT}`)
} )

i really hope this problem solving of this code, thank you

Upvotes: 0

Views: 173

Answers (4)

Birender Pathania
Birender Pathania

Reputation: 494

Just you need to do is install cors by using below command:

   npm install core

   //Then use it in server file like this: 
   var cors = require('cors')
   app.use(cors())

Upvotes: 0

tri putra
tri putra

Reputation: 5

finally i've got this solve

i miss the set proxy server of the front end site, thanks !

Upvotes: 0

Yoandry Collazo
Yoandry Collazo

Reputation: 1212

You are calling your API on localhost:3000, but your API should be running on localhost:5001

 const { data } = await axios.get("http://localhost:5001/api/products");

Upvotes: 2

Hyetigran
Hyetigran

Reputation: 1215

You want to initialize your state with brackets "[]" instead of "{}"

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

Also, you might want to code defensively by adding a turnery operation to check to see if products is 'truthy' if it's not, then the user will see some kind of error message i.e. the part after the ":".

{products ? products.map( product => {}) : <div>handle error</div> }

Upvotes: 0

Related Questions