从 API 获取的补丁数据

问题描述

我是初学者,正在尝试创建一个练习项目。我正在尝试“修补”从 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

如果您想更新(PATCHavailableSpotclass 字段,id 为 1,您应该使用 http://localhost:8000/classes/1

一个有效的example

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...