【问题标题】:Setting cookie in a Nuxt 3 (npm run dev) server from a Golang Echo API从 Golang Echo API 在 Nuxt 3 (npm run dev) 服务器中设置 cookie
【发布时间】:2022-11-18 13:54:43
【问题描述】:

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

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

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

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

我尝试按照Set cookies for cross origin requests 的提示进行操作,但无济于事。我不确定这是否是我的问题。

我什至尝试从 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,
 }))

session.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())

authStore.js (pinia)

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

我可以来自 Nuxt 前端的 cookie useCookie(),但我不知道如何拿来网络选项卡中已经存在的 set-cookie。

【问题讨论】:

    标签: go echo gorilla nuxtjs3


    【解决方案1】:

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

    
    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 }
    
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-20
      • 1970-01-01
      • 2022-11-14
      • 2019-08-05
      • 2019-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多