如何使用 adonis 后端对 nuxt 前端使用会话身份验证

How to use session authentication for nuxt frontend with adonis backend

我以前用过 adonuxt,效果不错,但它已经贬值了。所以我现在尝试使用 nuxt.js 与 adonis 后端分开。我正在尝试制作登录系统。这两个项目 运行 在本地主机的两个独立端口上。 http://localhost:3000/ nuxt 项目和 http://localhost:3333/ adonis 项目。

如何在nuxtServerInit中获取登录用户信息?

我正在尝试这样

async nuxtServerInit({ commit }, { $axios }) {
 console.log('I am running as nuxt server init')

 try {
   // get the initial data
   let { data } = await axios.get('http://localhost:3333/myuser')
   commit('loginUser', data)
 } catch (e) {
     console.log('nuxt server error ', e.response)
  }
},

在我的 adonis.js 中,我正在尝试

async getUser({request, response, params, auth}){
  try {
    const user = await auth.getUser()
    return user
  } catch (error) {
      return 'not logged in'
  }
}

结果总是not logged in.....

知道如何实施......

更新

我使用的是一个非常简单的登录系统

async user({request, response, params, auth}){
   try {
      const user = await auth.loginViaId(34)
      return user
   } catch (error) {
      return error
   }
}

我现在得到了一个非常有趣的结果。因此,如果我使用我的 adonis 项目登录,则登录用户信息在 nuxt 项目中可用,但如果我使用 nuxt axios

登录,我将无法获得登录用户

更新 2

因此,session 登录有效,但是当使用 axios 时,adonis 找不到用户或登录用户。

更新 3

我们只能使用 nuxtServerInit 获取登录用户。我们可以使用 axios 获取登录用户。:(

配置阿多尼斯

config/session.js

  cookie: {
    httpOnly: true,
    path: '/',
    sameSite: 'strict',
    domain: Env.get('COOKIE_DOMAIN', null),
  },

config/cors.js

  /*
  |--------------------------------------------------------------------------
  | Credentials
  |--------------------------------------------------------------------------
  |
  | Define Access-Control-Allow-Credentials header. It should always be a
  | boolean.
  |
  */
  credentials: true, // Enable credentials cookies

The Access-Control-Allow-Credentials response header tells browsers whether to expose the response to frontend JavaScript code when the request's credentials mode (Request.credentials) is include.

有关 Access-Control-Allow-Credentials header 的更多信息:developer.mozilla.org

配置 Nuxt

启用 axios 凭证(https://axios.nuxtjs.org/options.html#credentials):

nuxt.config.js

  axios: {
    credentials: true,
  },