0

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

4 Answers 4

2

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");
Sign up to request clarification or add additional context in comments.

1 Comment

thank you of the questions. and this code, i forgot to set the proxy server of package.json ckck
0

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> }

1 Comment

i've tried change "{}" to "[]" and still error : GET localhost:3000/api/products 404 (Not Found)
0

finally i've got this solve

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

Comments

0

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())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.