尝试使用Prisma和Zod在我的Next.js应用程序中删除帖子时出错

ws51t4hk  于 2023-08-04  发布在  其他
关注(0)|答案(2)|浏览(113)

我目前正在做一个Next.js项目,我试图通过它的**id删除一篇文章,使用Prisma作为我的ORM和Zod进行数据验证。客户端组件向我服务器上的API路由发送DELETE请求,请求体中应该包含要删除的post的id**。
下面是处理删除的客户端函数:

const handleDelete = async () => {
  if (!post?.id) return;
  try {
    await axios.delete(`/api/subreddit/post/delete/`, {
      data: { postId: post.id },
    });
    toast({
      title: "Success",
      description: "Post was deleted successfully",
    });
    router.refresh(); // Refresh the page or redirect the user.
  } catch (error) {
    console.log(error); // Log the error message
    return toast({
      title: 'Something went wrong.',
      description: "Post wasn't deleted successfully. Please try again.",
      variant: 'destructive',
    })
  }
};

字符串
我的服务器端函数看起来像这样:

export async function DELETE(req: Request) {
  try {
    const body = await req.json();
    const { postId } = z.object({
      postId: z.string(),
    }).parse(body);

    const session = await getAuthSession();

    if (!session?.user) {
      return new Response("Unauthorized", { status: 401 });
    }

    const post = await db.post.findUnique({
      where: {
        id: postId,
      },
    });

    if (!post) {
      return new Response("Post not found", { status: 404 });
    }

    if (post.authorId !== session.user.id) {
      return new Response("You do not have permission to delete this post", { status: 403 });
    }

    await db.post.delete({
      where: {
        id: postId,
      },
    });

    return new Response("Post Deleted");
  } catch (error:any) {
    console.log('Error when deleting post:', error.message);
    if (error instanceof z.ZodError) {
      return new Response(error.message, { status: 400 });
    }

    return new Response(
      "Could not delete post at this time. Please try later",
      { status: 500 }
    );
  }
}


当我尝试删除一个帖子时,我得到以下错误:

[
  {
    "code": "invalid_type",
    "expected": "string",
    "received": "undefined",
    "path": [
      "postId"
    ],
    "message": "Required"
  }
]


此错误表明**postIdundefined。我不知道为什么会发生这种情况,因为我在客户端的DELETE请求中提供了postId**。任何帮助将不胜感激!
我试图控制台日志的请求,并试图找出问题从那里,但我没有成功。

1yjd4xko

1yjd4xko1#

更新next.js修复了这个问题,因为这是next.js中的一个bug。

ukdjmx9f

ukdjmx9f2#

我运行了您的代码,但对Axios主体使用了文字字符串“test”。
完成此操作后,解析没有失败,代码按预期工作。
验证post.id类型是100%字符串,否则,我没有看到问题。
下面是我使用的mock代码:
第一个月

import { NextResponse } from "next/server"
import { z } from "zod"

export async function DELETE(req: Request) {
  try {
    const body = await req.json()
    const { postId } = z
      .object({
        postId: z.string(),
      })
      .parse(body)

    return NextResponse.json("success", { status: 200 })
  } catch (error: any) {
    console.log("Error when deleting post:", error.message)
    if (error instanceof z.ZodError) {
      return new Response(error.message, { status: 400 })
    }

    return new Response(
      "Could not delete post at this time. Please try later",
      { status: 500 }
    )
  }
}

字符串
client code:

"use client"

import axios from "axios"

import { Button } from "@/components/ui/button"

const page = () => {
  return <Button onClick={handleDelete}>delete</Button>
}
export default page

const handleDelete = async () => {
  try {
    await axios.delete(`/api/delete`, {
      data: { postId: "test" },
    })
  } catch (error) {
    console.log(error)
  }
}

相关问题