为什么我会收到 [next
我最近从 next-auth 4.19 更新到 4.22.1.
更新之前,我的代码运行良好。
我有一个 API 路由,在那个代码中,我有一个简单的:
export default async function handler(req, res) {
if (req.method === 'POST') {
//first, check if they're logged in.
console.log("test54646");
const session = await getSession({ req });
console.log("test789987977");
...
//return a JSON object.
在更新之前,代码工作完成(它返回一个 JSON 对象)。
更新后报错:
test54646
[next-auth][error][CLIENT_FETCH_ERROR]
undefined {
error: {},
url: 'http://localhost:3000/api/auth/session',
message: undefined
}
test789987977
getSession({req}) 好像报错了?
奇怪的是,如果我直接在浏览器中点击 URL: http://localhost:3000/api/auth/session
工作正常。我的浏览器显示了它应该返回的 JSON 对象。
我在以下位置查找了此错误的文档:
它只是说我必须配置 NEXTAUTH_URL 环境变量。
所以我进入 .env.local,并设置: NEXTAUTH_URL=http://localhost:3000
我仍然有错误。
谁能解释一下如何解决这个问题?我真的很想升级到 4.22,因为新的 update() 和 refresh() 功能:
谢谢。
回答如下:我找到了解决方案:
原来,如果它在服务器上执行,你使用 getServerSession(),但如果你在客户端,你使用 getSession()。我猜它在 4.19 中在服务器端使用 getSession() 工作正常,但在 4.22.1 中,它给出了错误。文档说在服务器端使用 getSession() 仍然可以,但它不再适用于我。
资料来源: https://next-auth.js/configuration/nextjs#unstable_getserversession
请参阅标题为“在 API 路由中”的部分