typeerror - 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
解决方案
找到了答案:那是核心错误。你只需要添加cors。
var cors = require('cors');
app.use(cors(), (req, res, next) = {}
推荐阅读
- django - Django CBV 方法触发顺序
- php - php exec 在动态添加值时返回错误代码为 1
- c# - 正则表达式和 (char)30 我如何定义
- kotlin - Kotlin 安全成对迭代
- node.js - 由于恶意软件,Google Adwords 拒绝了我的广告系列,但我清理了代码
- c# - 在 Outlook 中添加 XtraReport 作为附件
- spring - 关于布局,如何使用 Thymeleaf 和 Spring 在新的浏览器选项卡或窗口中保持在菜单上执行的操作?
- vb.net - 如何读取 txt 文件中的行,然后在 TextBox VB.NET 中仅显示某些字符?
- assembly - _SFR_IO8(0x04) 在做什么?AVR
- spring - Spring - 将外部实体设置为属性