我具有客户端组件GetUserInfoButton
.在该组件中,我在URL http://localhost:3000/test/users/[id]
上发送了一个GET请求,其中[id]
是一个类似MongoDB字母数字序列.
在app/api/users/[id]/route.ts
内,我希望接收该请求并使用该[id]
.以下是我的GetUserInfoButton
个组成部分:
'use client';
export default function GetUserInfoButton({ id }: { id: string }) {
const contentType = "application/json";
const handleClick = async (id: string) => {
try {
const res = await fetch(`/api/users/${id}`, {
method: "GET",
headers: {
"Content-Type": contentType,
}
});
if (!res.ok) {
throw new Error(res.status.toString());
}
} catch (error) {
console.log("error ===> ", error);
}
};
return (
<button onClick={() => handleClick(id)}>
Get
</button>
);
}
这是我的route.ts
%文件:
import { NextRequest, NextResponse } from "next/server";
export async function GET(req: NextRequest) {
const id = req.url.split("http://localhost:3000/api/users/")[1];
return NextResponse.json({
success: true,
id: id
}, {
status: 200,
})
}
当它还是Pages路由时,我可以在客户机上使用useRouter(
),并在服务器上获得id,如下所示:
const { query: { id } } = req
.
如何在服务器组件中获取id参数?
我使用的是Next.js 13.4.16
.