如何在Nuxt中使用nuxtServerInit作为中间件

时间:2018-02-16 07:57:11

标签: node.js nuxt.js

我将我的应用程序拆分为serverclient一个。我正在运行服务器并在快递中使用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文件不再具有此功能。它以这种方式工作。

2 个答案:

答案 0 :(得分:1)

nuxtServerInit操作只能在商店index.js文件中使用(或者在创建商店的另一个单词中)。

因此,请尝试将nuxtServerInit移到那里。

答案 1 :(得分:-1)

我有一个问题,我在store / index.js中写了nuxtServerInit,

  nuxtServerInit ({ commit }, { req }) {
    if (req.session && req.session.authUser) {
      console.log('SET_USER')
      console.log(req.session.authUser)
      commit('SET_USER', req.session.authUser)
    }
  },

nothing happend