生产环境中的下一个 js + Node js cookie 问题

问题描述 投票:0回答:1

安装程序在本地环境中完美运行。当我在 AWS 中托管它时出现擦除问题。 Node.js/Express 在 AWS Fargate、docker 中运行,位于 ALB 后面。 Next.js (v 14) 托管在 amplify 中。前端和后端都是https。

我正在使用 Next js 中的服务器操作发送请求:

 const res = await fetch(`${appConfig.BASE_URL}${loginUrl}`, {
  method: 'POST',
  credentials: 'include',
  headers: {
    'Content-Type': 'application/json',
    Authorization: `Bearer ${accessToken}`,
  },
})

在 Node js 中,我有一个带有以下设置的 cors() 中间件

const corsOption = {
  origin: [appConfig.FRONT_END_BASE_URL, appConfig.FRONT_END_ADMIN_URL],
  preflightContinue: true,
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
  credentials: true,

}

这是登录控制器,我将 cookie 发送回客户端

 res.cookie('accessToken', sessionToken, {
      path: '/',
      httpOnly: true,
      sameSite: 'none',
      secure: true,
    })

但是,当我检查网络调用时,我可以看到服务器使用 cookie 进行响应,但浏览器未设置它。

这是一个请求

这是回复

但它没有设置 cookie

Brave 和 Firefox 都会发生这种情况,但是在 Chrome 中我可以看到 cookie 已设置,但我仍然无法登录,看起来 Next js 无法读取它或其他什么。

我正在使用“next/headers”中的 cookies 模块访问 Next js 中的 cookie

请帮忙找出问题所在。已经挣扎了3天了。

我的猜测可能与我从服务器操作发送请求(技术上不是客户端)这一事实有关?

node.js next.js cookies
1个回答
0
投票

这是我的2美分

首先,请将其包含在您的获取请求的标头中。

"Access-Control-Allow-Origin": "*",

其次 我猜你没有明确地从你的 Express 后端保存 cookie。为什么不尝试保存并查看结果呢?

"use server"

import { NextRequest, NextResponse } from "next/server"

export async function POST(request: NextRequest) {
    const { accessToken } = await request.json()

    const res = await fetch(`${appConfig.BASE_URL}${loginUrl}`, {
        method: "POST",
        credentials: "include",
        headers: {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "*",
            Authorization: `Bearer ${accessToken}`, // I did not understand why you add this to the header..
        },
    })

    const response = new NextResponse(JSON.stringify(res.data), {
        headers: {
            "Content-Type": "application/json"
        }
    })

    const cookieHeader = response.headers.get("Set-Cookie")
    if (cookieHeader) {
        response.headers.set("Set-Cookie", cookieHeader.join(","))
    }

    return response
}
© www.soinside.com 2019 - 2024. All rights reserved.