透過fetch回傳的結果,要用res.json();才能把資料存起來

.text()則是返回普通文本型的數據

get

onMounted(async () => {
  loading.value = true;

  const controller = new AbortController();

  try {
    // setTimeout(() => {
    //   controller.abort();
    // }, 500);

    // const res = await axios.get("/api/notes", {
    //   signal: controller.signal,
    // });
    const res = await fetch("/api/notes");
    notes.value = await res.json();
  } catch (e) {
    if (e?.response?.data) {
      error.value = e.response.data;
    }
  } finally {
    loading.value = false;
  }
});

post

傳遞數據的話,需要手動轉換成字符串 body: JSON.stringify(note),

async function handleNoteFormSubmit(note) {
  // const res = await axios.post("/api/notes", note, {
  //   // headers: {
  //   //   "Content-Type": "application/json",
  //   //   Authorization: "Bearer SOMEJWTTOKEN",
  //   // },
  // });

  const res = await fetch("/api/notes", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer SOMEJWTTOKEN",
    },
    body: JSON.stringify(note),
  });

  notes.value.push(await res.json());
}

處理錯誤

因為fetch的錯誤沒辦法直接拋給try catch (除非是因為網路出錯而請求失敗,這可以透過catch接住)

所以要透過自定義邏輯處理錯誤

onMounted(async () => {
  loading.value = true;

  const controller = new AbortController();

  // try {
  // setTimeout(() => {
  //   controller.abort();
  // }, 500);

  // const res = await axios.get("/api/notes", {
  //   signal: controller.signal,
  // });
  const res = await fetch("/api/notes");

  if (res.status > 400) {
    error.value = await res.json();
  } else {
    notes.value = await res.json();
  }

  // } catch (e) {
  // if (e?.response?.data) {
  //   error.value = e.response.data;
  // }
  // } finally {
  loading.value = false;
  // }
});

取消請求

fetch取消請求的邏輯和axios一樣

onMounted(async () => {
  loading.value = true;

  const controller = new AbortController();

  try {
    setTimeout(() => {
      controller.abort();
    }, 500);

    // const res = await axios.get("/api/notes", {
    //   signal: controller.signal,
    // });
    const res = await fetch("/api/notes", {
      signal: controller.signal,
    });

    if (res.status > 400) {
      error.value = await res.json();
    } else {
      notes.value = await res.json();
    }
  } catch (e) {
    // if (e?.response?.data) {
    //   error.value = e.response.data;
    // }
    console.log(e);
  } finally {
    loading.value = false;
  }
});

封裝fetch

src\composables\useRequest.js

async function useRequest(url = "", method = "GET", data) {
  const res = await fetch(url, {
    method,
    headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer SOMEJWTTOKEN",
    },
    body: data ? JSON.stringify(data) : undefined,
  });

  if (res.status > 400) {
    const error = await res.json();
    const e = new Error(res.statusText);
    e.error = error;
    e.status = res.status;
    throw e;
  }

  const result = await res.json();
  return result;
}

export default useRequest;