TypeError: failed to fetch mern
TypeError: failed to fetch 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
找到答案:那是核心错误。你只需要添加 cors.
var cors = require('cors');
app.use(cors(), (req, res, next) = {}
我正在学习课程“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
找到答案:那是核心错误。你只需要添加 cors.
var cors = require('cors');
app.use(cors(), (req, res, next) = {}