Search code examples
typeerrormern

TypeError: failed to fetch mern


I'm on Course "React, NodeJS, Express & MongoDB - The MERN Fullstack Guide" Section "Connecting the React.js Frontend to the Backend". Can anyone guide me on why I'm getting this error? Whenever I Update or delete a place it shows the error: TypeError: Failed to fetch What can I do about that?

enter image description here

const UserPlaces = () => {
const [loadedPlaces, setLoadedPlaces] = useState();
const { isLoading, error, sendRequest, clearError } = useHttpClient();

const userId = useParams().userId;

useEffect(() => {
    const fetchPlaces = async () => {
        try {
            const responseData = await sendRequest(
                `http://localhost:5000/api/places/user/${userId}`
            );
            setLoadedPlaces(responseData.places);
        } catch (err) { }
    };
    fetchPlaces();

}, [sendRequest, userId]);

const placeDeletedHandler = deletedPlaceId => {
    setLoadedPlaces(prevPlaces =>
        prevPlaces.filter(place => place.id !== deletedPlaceId)
    );
};

return (
    <React.Fragment>
        <ErrorModal error={error} onClear={clearError} />
        {isLoading && (
            <div className="center">
                <LoadingSpinner />
            </div>
        )}
        {!isLoading && loadedPlaces && <PlaceList items={loadedPlaces} onDeletePlace={placeDeletedHandler} />}
    </React.Fragment>
);
};

export default UserPlaces;

Frontend: https://github.com/sharjeelyunus/peek-mern Backend: https://github.com/sharjeelyunus/peek-mern-api


Solution

  • Found the answer: that was the cores error. you just have to add cors.

    var cors = require('cors');
    
    app.use(cors(), (req, res, next) = {}