Nextjs 带有凭据的 GET 请求,API 路由不接收(未定义)cookie,而对同一路由的 POST 请求接收正确的值

Nextjs GET request with credentials, API route doesn't receives ( undefined ) cookies while POST request to same route receives correct values

提问人:SmartphonE_Codes 提问时间:11/17/2023 更新时间:11/17/2023 访问量:21

问:

该应用程序在 localhost 上运行良好,但在部署到 Vercel 时,我会遇到这个错误,每当我使用凭据执行 GET 请求时,API 路由都会收到未定义,但是当我对同一路由执行 POST 请求时,会正确接收 cookie。

如果有人能向我解释这一点,那将是非常有帮助的,提前致谢:)

这是 Get 请求(发送 cookie,但在 API 路由上接收未定义):-

let reqHeaders = new Headers()
reqHeaders.append("Content-Type", "application/json")

//GET request
fetch(`${APP_URL}/api/validateLoginSession`,{
    method: "GET",
    headers: reqHeaders,
    credentials: "include"
}).then(it=>{
    it.json().then(resp=>{
        resp.isValid ? onSuccess() : onFailure()
    })
})

// on api/validateLoginSession/route.ts    
export async function GET(req: NextRequest) {

    const userId = req.cookies.get("userId")?.value // receives undefined
    const logToken = req.cookies.get("logToken")?.value // receives undefined

    if (userId && logToken) {
        // ...

    }else{
        // ...
    }

    return new Response(JSON.stringify({isValid: false}))
}

但是 POST 请求在同一路由上:

// POST request to same route
fetch(`${APP_URL}/api/validateLoginSession`,{
    method: "POST",
    headers: reqHeaders,
    credentials: "include",
    body: JSON.stringify({data: "null"})
}).then(it=>{
    it.json().then(resp=>{
        resp.isValid ? onSuccess() : onFailure()
    })
})

// on api/validateLoginSession/route.ts    
export async function POST(req: NextRequest) {

    const reqData = await req.json()
    const userId = req.cookies.get("userId")?.value // receives correct value
    const logToken = req.cookies.get("logToken")?.value // receives correct value

    if (userId && logToken) {
        // ...
    }else{
        // ...
    }

    return new Response(JSON.stringify({isValid: false}))
}
node.js next.js cookie 部署 vercel

评论


答: 暂无答案