英文:
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())
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论