我目前正在开发一个 Next.js 项目,我正在尝试使用 Prisma 作为我的 ORM 和 Zod 进行数据验证,通过其
id
删除帖子。客户端组件向我的服务器上的 API 路由发送 DELETE 请求,并且应在请求正文中包含要删除的帖子的 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"
}
]
此错误表明
postId
是 undefined
。我不确定为什么会发生这种情况,因为我在客户端的 DELETE 请求中提供了 postId
。任何帮助将不胜感激!
我尝试控制台记录请求并尝试从那里找出问题,但没有成功。
我运行了你的代码,但对 Axios 主体使用了文字字符串“test”。
这样做之后,解析没有失败,并且代码按预期工作。
验证 post.id 类型是否 100% 是字符串,否则,我看不出有问题。
这是我使用的模拟代码:
Server code:
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)
}
}
更新 next.js 修复了问题,因为这是 next.js 中的错误。