NEXT_AUTH会话在POST方法中不可用

krcsximq  于 2023-06-29  发布在  其他
关注(0)|答案(1)|浏览(86)

我正在使用Google作为提供商实现NextAuth身份验证。我还集成了MongoDB作为DB。在API端点上,我使用getSession获取会话。但是会话在POST方法中将变为null,并且可以很好地处理GET请求。

getDocs.js

import { getSession } from "next-auth/react"

export default async function handler(req,res){

    if(req.method!="GET") res.status(400).json({status:"error",msg:"Cannot fulfil GET API request"})

    const session = await getSession({req})

        console.log(session)  // session is there. Works fine

    // further code

}

updateDoc.js

import { getSession } from "next-auth/react"
import connectDB from "../../../lib/dbconnect/dbconnect"
import Document from "../../../lib/models/document"
import clientPromise from "@/lib/mongodb"

connectDB()

export default async function handler(req,res){
    
    console.log(req.body)
    
    if(req.method !== "POST")  res.status(400).json({status: "error", msg: "Cannot fulfill GET API request"})

    const session = await getSession({req})
        
        console.log(session)  // session is null. Works fine

    // further code
}

API/auth/[…nextauth].js

import NextAuth from "next-auth"
import GoogleProvider from "next-auth/providers/google"
import clientPromise from "../../../lib/mongodb"
import { MongoDBAdapter } from "@next-auth/mongodb-adapter"

export const authOptions = {
  providers: [
    GoogleProvider({
      clientId: process.env.NEXTAUTH_GOOGLE_CLIENT_ID,
      clientSecret: process.env.NEXTAUTH_GOOGLE_CLIENT_SECRET,
    }),
  ],
  pages:{
    signIn:'/signin'
  },
  adapter: MongoDBAdapter(clientPromise),
  
}

export default NextAuth(authOptions)

我发现它对get请求工作得很好,因为我在删除if条件以检查方法类型后尝试向updateDoc.js发出get请求,它工作得很好。
我该怎么办?

zujrkrfu

zujrkrfu1#

找到了问题的答案
使用getServerSession代替getSession

相关问题