问题描述
我是初学者,正在尝试创建一个练习项目。我正在尝试“修补”从 API 获取的数据。 我的 json 文件如下所示:
{
"classes": [
{
"title": "Office Syndrome","length": "60 Minutes","instructor": "A. W.","difficulty": "Intermediate","description": "Suitable for people who are always constantly inactive working in front of computers.","availableSpot": "10","id": 1
},{
"title": "Digestive Flow","instructor": "MJ","difficulty": "Beginners","description": "Good for digestion","availableSpot": "8","id": 2
}
]
我正在尝试创建一个可预订课程的功能,每次预订后,availableSpot 将减少 1。
我的 handleBook 函数目前看起来像这样:
const handleBook = (index) => {
setSelectedYogaClass(true);
if (selectedYogaClass === index) {
fetch("http://localhost:8000/classes",{
method: "PATCH",headers: { "Content-Type": "application/json" },body: JSON.stringify({ availableSpot: data.availableSpot - 1 }),})
.then((res) => {
if (!res.ok) {
throw Error("Sorry,something went wrong");
}
})
.then((res) => {
console.log(res);
})
.catch((err) => {
setBookingError(err);
});
}
console.log(selectedYogaClass);
setModalisOpen(false);
};
<button
key={index}
onClick={() => handleBook(index)}
className="button button--outline"
>
Yes
</button>
但是,我收到 404 错误并且想知道问题是什么? 谁能指出我做错了什么?
在此先感谢您!
解决方法
使用 plural routes 时需要指定特定资源,例如 http://localhost:8000/classes/:id
。
如果您想更新(PATCH
)availableSpot
的 class
字段,id 为 1
,您应该使用 http://localhost:8000/classes/1
一个有效的example