0
votes

I try to fetch a list in Reacjs component. I create my API in Laravel but when i try to fetch a list it gives me this error message in console

**Access to fetch at 'http://localhost:8000/api/puppies' from origin 'http://localhost:3000' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values ', ', but only one is allowed. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

my card component file

import React, {useState, useEffect}  from 'react';
import {Link} from 'react-router-dom';
import {getPuppies} from "./apiCore";

const Card = () => {
const [allPets, setAllPets] = useState([]);
const [error, setError] = useState(false);

const loadAllPets = () => {
    getPuppies().then(data => {
        if(data.error){
            setError(data.error)
        } else{
            setAllPets(data)
        }
    });
    };

    useEffect(() =>{
     loadAllPets();
    }, [])

   return(
    <div>
        <div className="row">
            <div className="col-lg-4 col-md-6 col-12">
                {JSON.stringify(allPets)}
            </div>
        </div>
    </div>
    ) 
}
export default Card;

apiCore.js

import {API} from "../config";

export const getPuppies = () =>{
 return fetch(`http://localhost:8000/api/puppies`, {
    method: "GET",
})
.then(response =>{
    return response.json();      
})
.catch(err =>{
    console.log(err);
});

};

Please help.

error image

1

1 Answers

0
votes

It's a server side error. You need to set up CORS in your server side API.

If you are using expressjs, you can set it by using this