簡體   English   中英

從 API 獲取的補丁數據

[英]Patch data fetched from 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",
      "length": "60 Minutes",
      "instructor": "MJ",
      "difficulty": "Beginners",
      "description": "Good for digestion",
      "availableSpot": "8",
      "id": 2
    }
]

我正在嘗試創建一個功能,其中 class 可預訂,每次預訂后 availableSpot 將減少 1。

我的 handleBook function 目前看起來像這樣:

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);
  };

這就是我如何稱呼 function

 <button
                    key={index}
                    onClick={() => handleBook(index)}
                    className="button button--outline"
                  >
                    Yes
                  </button>

但是,我收到 404 錯誤,想知道問題出在哪里? 誰能指出我做錯了什么?

非常感謝您!

當您使用http://localhost:8000/classes/:id多個路由時,您需要指定特定資源。

如果要更新( PATCH ) id 為1classavailableSpot字段,則應使用http://localhost:8000/classes/1

一個工作示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM