在这里完全被难住了.
我正在与办事员一起工作,我希望使用getAuth()帮助器访问当前用户的userid.
此处的文档数量:https://clerk.com/docs/references/nextjs/get-auth
pages/api/example.ts
import { getAuth } from "@clerk/nextjs/server";
import type { NextApiRequest, NextApiResponse } from "next";
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const { userId } = getAuth(req);
// Load any data your application needs for the API route
return res.status(200).json({ userId: userId });
现在,当我在浏览器中访问此终结点时:
http://localhost:3000/api/example
它似乎起作用了,因为我在浏览器中看到了打印的用户ID:
{"userId":"user_2Ze2xqQyKbZbsXaZi7cv1sXLf2S"}
但是,当我try 在getServerSideProps函数中调用此API端点时,我收到:{ userId: null }
pages/profile.tsx
export async function getServerSideProps() {
const res = await fetch(`http://localhost:3000/api/example`);
const data = await res.json()
console.log(data) // this logs: { userId: null }
return {
props: {
properties: data,
},
};
}
我的中间件文件:
middleware.ts
import { authMiddleware } from "@clerk/nextjs";
export default authMiddleware({
publicRoutes: ["/api/example", "/profile"],
});
export const config = {
matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'],
};
有人能找出问题所在吗?我一整天都被困在这上面了.感谢您的关注