首页 > 解决方案 > 如何使用 Vue.js、Vuex、Express、MongoDB 检索 currentUser 数据

问题描述

我正在尝试构建一个 MEVN 堆栈身份验证页面,该页面返回有关当前登录用户的信息。登录后,路由器重定向到 Home.vue,同时将 传递username给 Home.vue 作为道具。

Login.vue 中的 onSubmit 方法

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

然后在 Home.vue 组件中分派一个 Vuex 操作,该组件将用户名传递给 store.js 中的操作处理程序

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

商店从 Express 路由中请求登录用户的用户名,该路由设置为基于 URL 搜索登录用户,并username作为查询:

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

特快路线

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

登录用户的用户名检索成功,返回模板:

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

但是...一旦我刷新浏览器,用户名就会消失。知道为什么名字不会留在屏幕上吗?它与作为道具传递给 Home.vue 的用户名有关吗?而不是将用户名道具一直传递给:

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

...是否有另一种方法可以将登录用户的用户名作为 URL 中的查询传递?

更新的 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]
})

标签: javascriptnode.jsmongodbexpressvue.js

解决方案


在 Vue/Vuex 中,一旦刷新页面或转储缓存,状态就会被清除。如果你想持久化数据,你有几个选择。

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.


推荐阅读