How to retrieve currentUser data with Vue.js, Vuex, Express, MongoDB

耗尽温柔 提交于 2020-01-16 12:04:17

问题


I am attempting to build a MEVN stack authentication page that returns information on the currently logged-in user. Upon logging in, the router re-directs to the Home.vue while passing the username to the Home.vue as a prop.

onSubmit method in Login.vue

<script>
  methods: {
    onSubmit (evt) {
      evt.preventDefault()
      axios.post(`http://localhost:3000/api/auth/login/`, this.login)
        .then(response => {
          localStorage.setItem('jwtToken', response.data.token)
          this.$router.push({
            name: 'BookList',
            params: { username: this.login.username }
          })
        })
        .catch(e => {
          this.errors.push(e)
        })
      },
      register () {
        this.$router.push({
          name: 'Register'
        })
      }
    }
  }
  </script>

A Vuex action is then dispatched in the Home.vue component, which passes the username to an action handler in store.js

Instance in Home.vue

import axios from 'axios'
import { mapState } from 'vuex'
export default {
  name: 'BookList',
  props: ['username'],
  data () {
    return {
      errors: []
    }
  },
  computed: mapState([
    'users'
  ]),
  created () {
    this.$store.dispatch('setUsers', this.username)
  }
}
</script>

store.js

import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    users: [],
  },
  mutations: {
    setUsers: (state, users) => {
      state.users = users
    }
  },
  actions: {
    setUsers: async (context, username) => {
      let uri = `http://localhost:3000/api/auth/currentuser?username=${username}`
      const response = await axios.get(uri)
      context.commit('setUsers', response.data)
    }
  }
})

The store requests the username of the logged-in user from an Express route set up to search for the logged-in user based on a URL with username as a query:

http://localhost:3000/api/auth/currentuser?username=${username}

Express Route

router.get('/currentuser', function(req, res) {
  let params = {},
  username = req.query.username
  if (username) {
     params.username = username
  }
  User.find(params, function (err, users) {
    if (err) return next(err);
    res.json(users);
  });
});

The username of the logged-in user is successfully retrieved and returned to the template:

      <table style="width:100%">
        <tr>
          <th>Logged in User</th>
        </tr>
        <tr v-for="user in users" :key="user._id">
          <td>{{ user.username }}</td>
        </tr>
      </table>

HOWEVER...as soon as I refresh the browser, the username disappears. Any idea why the name does not stay on the screen? Does it have something to do with the username being passed into Home.vue as a prop? Instead of passing the username prop all the way to:

http://localhost:3000/api/auth/currentuser?username=${username}

...is there perhaps another way that I could pass the username of the logged-in user as a query in the URL?

UPDATED STORE.JS

import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import VuexPersistence from 'vuex-persist'

const vuexLocal = new VuexPersistence({
  storage: window.localStorage
})

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    users: [],
  },
  mutations: {
    setUsers: (state, users) => {
      state.users = users
    }
  },
  actions: {
    setUsers: async (context, username) => {
      let uri = `http://localhost:3000/api/auth?username=${username}`
      const response = await axios.get(uri)
      context.commit('setUsers', response.data)
    }
  },
  plugins: [vuexLocal.plugin]
})


回答1:


In Vue/Vuex, the state is wiped clean once you refresh the page or dump the cache. If you want to persist the data, you have a few choices.

  • You can use a plugin: https://github.com/championswimmer/vuex-persist
  • You can store the username in the localStorage.
  • You can store the information in cookies.

If you store them locally, it's a good idea to use Tokens or another security measure if you're worried about what users could do with locally stored data.



来源:https://stackoverflow.com/questions/59200408/how-to-retrieve-currentuser-data-with-vue-js-vuex-express-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!