最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

firebase authentication - Issues with the DELETE API handler in next.js - Stack Overflow

programmeradmin3浏览0评论

I am trying to remove the item from wishlist, and I am using firebase as the database and backend, however it seems there is some issues with the way the API is handling the DELETE request from the frontend:

here is my frontend code:

async function toggleWishlist(selectedItem) {
    const user = auth.currentUser;
    if (!user) {
      alert("You must be signed in to Wishlist products");
      return;
    }

    const existingItem = wishlist.find((item) => item.id === selectedItem.id);
    if (existingItem) {
      try {
        const res = await fetch(
          "/api/removewishlist",
          {
            method: "DELETE",
            headers:{'Content-type': 'application/json'},
            body:JSON.stringify({
              id: selectedItem.id,
              uid: user.uid,
              name: selectedItem.productName
            })
          }
        );

        if (!res.ok) {
          throw new Error("Failed to remove item from wishlist");
        }

        const data = await res.json();
        setWishlist((prev) =>
          prev.filter((item) => item.id !== selectedItem.id)
        );
      } catch (error) {
        console.error("Error removing item from wishlist", error.message);
      }
    }

    if (!existingItem) {
      try {
        const resp = await fetch("/api/addwishlist", {
          method: "POST",
          headers: { "Content-type": "application/json" },
          body: JSON.stringify({
            uid: user.uid,
            name:selectedItem.productName,
            id: selectedItem.id,
          }),
        });

        if (!resp.ok) {
          throw new Error("Failed to add item to wishlist");
        }

        const data = await resp.json();
        setWishlist((prev) => [...prev, selectedItem]);
      } catch (error) {
        console.error("Error adding item to wishlist", error.message);
      }
    }
  }

And here is my API handler code:

import { db } from "@/app/lib/firebaseconfig";
import { NextResponse } from "next/server";

export async function DELETE(req) {
  try {
    const { uid, id, name } = await req.json();

    if (!uid || !id || !name) {
      return NextResponse.json({ error: "Invalid request!" }, { state: 400 });
    }

    const wishListRef = db
      .collection("users")
      .doc(uid)
      .collection("wishlist")
      .doc(id);
    const docSnapshot = await wishListRef.get();

    if (!docSnapshot.exists) {
      return NextResponse.json(
        { error: "No such item exists in your wishlists" },
        { status: 404 }
      );
    }

    const wishlist = docSnapshot.data().wishlist || [];

    const updatedWishlist = wishlist.filter((item) => item.id !== id);

    await wishListRef.update({ wishlist: updatedWishlist });

    return NextResponse.json(
      { message: "Removed item from wishlist" },
      { status: 200 }
    );
  } catch (error) {
    console.error("Error removing wishlist item:", error);
    return NextResponse.json(
      { error: "Internal Server Error" },
      { status: 500 }
    );
  }
}

And when I am using this code I am getting an internal server error:

DELETE http://localhost:3000/api/removewishlist 500 (Internal Server Error)

Would appreciate if anyone can explain why this is happening, and what I can do to correct it

发布评论

评论列表(0)

  1. 暂无评论