简体   繁体   中英

How to use nuxtServerInit in Nuxt as middleware

I splitted my application into server and client one. I'm running server and using nuxt.render middleware in the express and I want to get my user/session/whatever in the nuxt storage. I've made a store/auth.js file:

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)
  }
}

Nothing happend when page loaded or action performed. There's git repository with complete server and client sides.

UPD For those, who looking for details : Make sure your nuxtServerInit function is in index.js file. You could move it like that:

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

And auth.js file have no this function anymore. It works in that way.

The nuxtServerInit action can only be used inside the store index.js file (or in another word where store is created).

So try to move your nuxtServerInit there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM