英文:
Unable to delete an entry from database using Next.js api routes with Prisma
问题
我正在开发一个待办事项管理器,并且一直在使用 Next.js 13、Prisma 和 MySQL。为了添加删除待办事项的选项,我已经使用 Link
标签包装了删除按钮,代码如下:
...
<Link href={`/api/todo/${id}`}>
<MdDelete className="bg-red-400 hover:bg-red-600 p-1 text-3xl rounded-xl" />
</Link>
...
其中,id
作为一个属性传递给组件。/app/api/todo/[id]/route.ts
文件如下:
import { prisma } from "@/lib/database";
import { NextResponse } from "next/server";
export async function DELETE(
req: Request,
{ params }: { params: { id: string } }
) {
await prisma.todo.delete({
where: {
id: params.id,
},
});
return NextResponse.json({ message: "done" });
}
但是当点击链接时,它跳转到URL http://localhost:3000/api/todo/clkgkh3t70000p1947hi24a3k
并显示以下页面:
其中 clkgkh3t70000p1947hi24a3k
是传递的 id
。
是否有解决此问题的方法?或者有没有其他方法来删除此待办事项?
英文:
So I am working on a Todo manager and have been using Next.js 13, Prisma, and MySQL for the same. To add an option to delete a todo item, I have wrapped the delete button with a Link
tag as follows:
...
<Link href={`/api/todo/${id}`}>
<MdDelete className="bg-red-400 hover:bg-red-600 p-1 text-3xl rounded-xl" />
</Link>
...
where id
is passed as a prop to the component. The /app/api/todo/[id]/route.ts
is as follows:
import { prisma } from "@/lib/database";
import { NextResponse } from "next/server";
export async function DELETE(
req: Request,
{ params }: { params: { id: string } }
) {
await prisma.todo.delete({
where: {
id: params.id,
},
});
return NextResponse.json({ message: "done" });
}
But when the Link is pressed, it goes to the URL http://localhost:3000/api/todo/clkgkh3t70000p1947hi24a3k
and shows the following page:
where clkgkh3t70000p1947hi24a3k
is the id
being passed.
Is there a fix to this issue? Or what is the alternative to remove this Todo Item?
答案1
得分: 1
Link
组件是围绕 HTML a
元素的包装器,通过设计将您带到新页面。您需要使用带有 onClick
的 button
:
<MdDelete
onClick={async (e) => {
e.preventDefault()
await fetch(`/api/todo/${id}`, { method: "DELETE" });
// 然后您可以重定向,或刷新状态等...
}}
className="bg-red-400 hover:bg-red-600 p-1 text-3xl rounded-xl"
/>
英文:
The Link
component is a wrapper around the HTML a
element, which takes you to a new page by design. You need to use a button
with an onClick
:
<MdDelete
onClick={async (e) => {
e.preventDefault()
await fetch(`/api/todo/${id}`, { method: "DELETE" });
// You can then redirect, or refresh a state, etc...
}}
className="bg-red-400 hover:bg-red-600 p-1 text-3xl rounded-xl"
/>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论