NextAuth 的 getServerSession 在 POST API 上可行,但在 GET 上不可行。

huangapple go评论61阅读模式
英文:

NextAuth getServerSession works on POST api but not GET

问题

某种原因,在POST路由上getServerSession函数能够工作,但在GET路由上却不行。

import { getServerSession } from "next-auth"
import { authOptions } from "../../auth/[...nextauth]/route"
import { NextResponse } from "next/server"

export async function GET(){
  const session = await getServerSession(authOptions)
  console.log("Session:", session)
  console.log("UserID:",session?.user.id)
  return NextResponse.json({posts: []}, {status: 200})
}
import { getServerSession } from "next-auth"
import { NextRequest, NextResponse } from "next/server"
import { authOptions } from "../../auth/[...nextauth]/route"

export async function POST(req: NextRequest){
    const session = await getServerSession(authOptions)
    if(!session) return NextResponse.json({message: "You don't have persmision!"}, {status: 401})
    //other code...
}

尝试模仿POST路由,结果仍然相同。

编辑:
它在/api上可以正常工作,但是在/api/posts/*上却不行,可能是某种路由问题吗?

编辑2:
在Postman上不起作用,但在浏览器调用API时却可以工作...?

英文:

For some reason getServerSession works on POST route but not on GET route.

import { getServerSession } from "next-auth"
import { authOptions } from "../../auth/[...nextauth]/route"
import { NextResponse } from "next/server"

export async function GET(){
  const session = await getServerSession(authOptions)
  console.log("Session:", session)
  console.log("UserID:",session?.user.id)
  return NextResponse.json({posts: []}, {status: 200})
}
import { getServerSession } from "next-auth"
import { NextRequest, NextResponse } from "next/server"
import { authOptions } from "../../auth/[...nextauth]/route"

export async function POST(req: NextRequest){
    const session = await getServerSession(authOptions)
    if(!session) return NextResponse.json({message: "You don't have persmision!"}, {status: 401})
    //other code...
}

tried to mimic POST route, still same result.

Edit:
It works on /api, but doesnt in /api/posts/* for some reason, can this be some kind of routing problem ?

Edit2: Doesn't work on postman, but works when calling api trough browser....?

答案1

得分: 1

解决方案:
如果您需要在路由的服务器端使用会话,您需要添加标头。

import { headers } from "next/headers";

在fetch内部:

headers: Object.fromEntries(headers())
英文:

Solution:
If you need session on server side in route, you need to add headers.

import { headers } from "next/headers"

Inside fetch:

headers: Object.fromEntries(headers())

huangapple
  • 本文由 发表于 2023年7月6日 21:30:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76629382.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定