首页 > 解决方案 > TypeError:未能获取 mern

问题描述

我在课程“React、NodeJS、Express 和 MongoDB - MERN 全栈指南”部分“将 React.js 前端连接到后端”。谁能指导我为什么会出现此错误?每当我更新或删除一个地方时,它都会显示错误:TypeError: Failed to fetch 我该怎么办?

在此处输入图像描述

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;

前端:https ://github.com/sharjeelyunus/peek-mern 后端:https ://github.com/sharjeelyunus/peek-mern-api

标签: typeerrormern

解决方案


找到了答案:那是核心错误。你只需要添加cors。

var cors = require('cors');

app.use(cors(), (req, res, next) = {}

推荐阅读