【问题标题】:Can not set cookies for nuxtServerInit无法为 nuxtServerInit 设置 cookie
【发布时间】:2020-12-11 08:14:10
【问题描述】:

我尝试使用 facebook 功能进行登录,我使用 rails 作为后端,使用 nuxtjs 作为客户端,在我从 facebook 接收数据并让用户之后,我想使用 access_token 重定向到客户端作为身份验证,我想保存 access_token饼干,但在nuxtServerInit 我不能做饼干。我也使用https://www.npmjs.com/package/cookie-universal-nuxt 来支持cookies

export async function nuxtServerInit ({ commit }, { store, route, req, res, app }) {
  if (route.query.token) {
    const token = `Bearer ${route.query.token}`
    store.commit(SET_STATE, { key: 'auth_info', value: { token: token } })
    this.$cookies.set('access_token', token)
  }
}

我检查网络以检查 cookie,但没有 cookie 保存在浏览器上。有人帮帮我吗?

我还阅读了其他问题here,但它不起作用。

更新:

我已经通过使用beforeNuxtRender 解决了这个问题,我认为 nuxtServerInit 是在设置 cookie 之前运行的。

export async function nuxtServerInit ({ commit }, { store, route, req, res, app, beforeNuxtRender }) {
  if (route.query.token) {
    const token = route.query.token
    let myProfile = null
    store.commit(SET_STATE, { key: 'auth_info', value: { token: token } })
    await store.dispatch('getUserProfile').then(res => {
      myProfile = res.data
      store.commit(SET_AUTH, { access_token: token, profile: myProfile })
    })
    beforeNuxtRender(({ nuxtState }) => {
      app.$cookies.set('access_token', token, { path: '/', maxAge: 60 * 60 * 24 * 180 })
      app.$cookies.set('my_profile', myProfile, { path: '/', maxAge: 60 * 60 * 24 * 180 })
    })
  }
}

【问题讨论】:

  • 试试 app.$cookies.set 而不是 this.$cookies.set
  • 记住:你不能在asyncDatanuxtServerInit中使用this
  • 谢谢,但app.$cookies.set 对我不起作用:(
  • 确认该功能与“cookie-universal-nuxt”一起为我工作。

标签: ruby-on-rails vue.js cookies nuxt.js


【解决方案1】:

嗯,您实际上拥有所需的一切。你有响应对象res,所以你可以这样做:

export async function nuxtServerInit ({ commit }, { store, route, req, res, app }) {
  if (route.query.token) {
    const token = `Bearer ${route.query.token}`
    store.commit(SET_STATE, { key: 'auth_info', value: { token: token } })
    res.cookie("access_token", token, {
      maxAge: 3600000,
    })
  }
}

【讨论】:

  • 我看到了错误res.cookie is not a function
猜你喜欢
  • 1970-01-01
  • 2018-11-28
  • 2019-09-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-28
  • 2021-03-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多