【问题标题】:How to use nuxtServerInit in Nuxt as middleware如何在 Nuxt 中使用 nuxtServerInit 作为中间件
【发布时间】:2018-02-16 07:57:10
【问题描述】:

我将我的应用程序分成serverclient 一个。我正在运行服务器并在 express 中使用 nuxt.render 中间件,我想在 nuxt 存储中获取我的用户/会话/任何内容。我制作了一个store/auth.js 文件:

export const state = () => ({
  user: null
})

export const mutations = {
  SET_USER: (state, user) => {
    state.user = user
  }
}

export const actions = {
  nuxtServerInit ({commit}, {req}) {
    console.log(req)
  },
  async login ({commit}, {username, password}) {
    try {
      const data = this.$axios.$post('/login', {username, password})
      commit('SET_USER', data)
    } catch (err) {
      throw err
    }
  },
  async logout ({commit}) {
    this.$axios.post('/logout')
    commit('SET_USER', null)
  }
}

页面加载或执行操作时没有发生任何事情。 git repository 有完整的服务器端和客户端。

UPD 对于那些寻找详细信息的人: 确保您的 nuxtServerInit 函数在 index.js 文件中。你可以这样移动它:

export const actions = {
  nuxtServerInit ({commit}, {req}) {
    if (req.user) commit('auth/SET_USER', req.user)
  }
}

auth.js 文件已经没有这个功能了。它以这种方式工作。

【问题讨论】:

    标签: node.js nuxt.js


    【解决方案1】:

    nuxtServerInit 操作只能在 store index.js 文件中使用(或者换句话说,在创建 store 的地方)。

    所以试着把你的nuxtServerInit 移到那里。

    【讨论】:

      猜你喜欢
      • 2020-06-23
      • 2020-04-23
      • 1970-01-01
      • 2020-09-12
      • 2019-02-27
      • 1970-01-01
      • 2021-10-27
      • 2020-05-13
      • 2020-07-15
      相关资源
      最近更新 更多