ชี้ URL ไปยัง resource ที่จะลบให้ชัด
ส่วนใหญ่ id ของ resource จะอยู่ใน path เช่น `/todos/1`
Fetch
โฟกัสการใช้ fetch() กับ DELETE requests ตั้งแต่ request shape การเช็ก response.ok และ status ไปจนถึงกรณีที่ response ไม่มี body กลับมา
เมื่อ frontend ต้องบอก server ให้ลบข้อมูล เช่น ลบ todo, ลบสินค้าในตะกร้า หรือ ลบบัญชีผู้ใช้ เรามักใช้ HTTP method เป็น **DELETE** เพื่อสื่อ intent ให้ชัดว่ากำลังลบ resource
async function deleteTodo(id) {
const response = await fetch(
`https://jsonplaceholder.typicode.com/todos/${id}`,
{
method: "DELETE",
}
);
if (!response.ok) {
throw new Error("ลบ todo ไม่สำเร็จ");
}
console.log("ลบ todo #" + id + " เรียบร้อย");
}
deleteTodo(1);| กรณี | สิ่งที่มักมี | สิ่งที่มักไม่ต้องมี |
|---|---|---|
| DELETE ทั่วไป | `method: 'DELETE'`, URL ที่ชี้ resource เป้าหมาย | body JSON |
| DELETE ที่ต้อง auth | headers เพิ่ม เช่น `Authorization` | body ถ้า API ไม่ได้ระบุ |
| DELETE แบบ custom API | อาจมี headers หรือ body เพิ่มตาม contract | ห้ามเดาเอง ต้องดู API spec |
ภาพรวมที่ควรจำคือ DELETE มักพึ่ง URL เพื่อบอกว่าจะลบ resource ไหน เช่น `/todos/1` ต่างจาก POST/PUT/PATCH ที่ต้องส่งข้อมูลใหม่เข้า body มากกว่า
DELETE สำเร็จไม่ได้แปลว่าจะต้องมี JSON body ตอบกลับเสมอไป หลาย API อาจตอบ `200 OK`, `202 Accepted` หรือ `204 No Content` ก็ได้ สิ่งที่เราสนใจก่อนคือ status สำเร็จหรือไม่
async function deleteTodoSafe(id) {
const response = await fetch(
`https://jsonplaceholder.typicode.com/todos/${id}`,
{ method: "DELETE" }
);
if (!response.ok) {
throw new Error(
`ลบ todo #${id} ไม่สำเร็จ (status: ${response.status})`
);
}
console.log("status:", response.status);
console.log("ลบสำเร็จ");
}จุดต่างสำคัญของ DELETE คือบาง API ตอบกลับแค่สถานะสำเร็จโดยไม่มี body เลย เช่น `204 No Content` ถ้าเราเรียก `response.json()` แบบเหมารวมทุกกรณีอาจเกิด parse error ได้
async function deleteTodoWithOptionalBody(id) {
const response = await fetch(
`/api/todos/${id}`,
{ method: "DELETE" }
);
if (!response.ok) {
throw new Error("ลบไม่สำเร็จ");
}
if (response.status === 204) {
return { deleted: true };
}
return response.json();
}ในงานจริงการลบสำเร็จมักไม่จบแค่ console log แต่ต้องสะท้อนผลกับ UI ต่อ เช่น เอารายการออกจาก state, redirect, หรือแสดงข้อความยืนยันให้ผู้ใช้เห็น แม้บทนี้ยังไม่ลงลึกเรื่อง state management แต่ควรเห็นภาพว่าผลจาก DELETE มักนำไปสู่ “อัปเดตหน้า” ทันที
ใช้ checklist นี้ทุกครั้งก่อนเขียนฟังก์ชันลบข้อมูลจริง
ส่วนใหญ่ id ของ resource จะอยู่ใน path เช่น `/todos/1`
404, 403 หรือ 500 ยังเป็นไปได้ แม้ request จะส่งถึง server แล้ว
DELETE บาง endpoint ตอบ `204 No Content` จึงไม่มี body ให้อ่าน