通过 Golang Echo API 在 Nuxt 3 (npm run dev) 服务器中设置 cookie

ake*_*ode 6 echo go gorilla nuxtjs3

我有一个 Nuxt 3 (^3.0.0-rc.11) 前端和一个 Golang Echo v4 后端 API。

该属性在 nuxt.config.ts 文件中ssr设置,因此当我运行时,我可以从 echo API 提供静态生成的文件,并且我从后端发送的会话 cookie 按预期在浏览器中设置。falsenpm run generate

但是,当我npm run dev从 nuxt 运行时,浏览器中没有设置 cookie,即使我可以在响应标头中看到它(在 Firefox 的网络选项卡下)。

我可能认为它不适用于开发服务器,因为 nuxt 正在端口上运行:3000并且 echo on :1323,并且可能存在 CORS 问题?

我尝试按照“为跨源请求设置 cookie”中的提示进行操作,但无济于事。我不确定这是否是我的情况的问题。

我什至尝试从v3.nuxtjs.org创建 nuxt 可组合项,但同样,我不确定这是否是问题所在。

服务器.go

e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
    AllowOrigins: []string{"http://localhost:3000"},
    AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept},
    AllowCredentials: true,
 }))
Run Code Online (Sandbox Code Playgroud)

会话.go

session, _ := store.Get(c.Request(), "session")
session.Options = &sessions.Options{
    Path:     "/",
    MaxAge:   86400 * 7, // 7 days
    HttpOnly: true,
    Secure:   true,
    SameSite: http.SameSiteNoneMode,
}
 session.Values["authenticated"] = true
 session.Values["user_id"] = user.ID
 session.Save(c.Request(), c.Response())
Run Code Online (Sandbox Code Playgroud)

authStore.js (pinia)

const { data } = await useAsyncData('login', () => $fetch(API_URL + '/api/login', {
    method: 'post',
    body: params,
    withCredentials: true,
})
Run Code Online (Sandbox Code Playgroud)

我可以使用useCookie()从 Nuxt 前端设置cookie ,但我不知道如何获取网络选项卡中已有的 set-cookie。

Kei*_*sud 1

当 cookie 由 API(即不是由 Nuxt)设置时,您可以使用getCookie()from 。h3


export default defineEventHandler(event =>
  // Read counter cookie
  let counter = getCookie(event, 'counter') || 0
  // Increase counter cookie by 1
  setCookie(event, 'counter', ++counter)
  // Send JSON response
  return { counter }

Run Code Online (Sandbox Code Playgroud)

https://nuxt.com/docs/api/composables/use-cookie/#handling-cookies-in-api-routes