如何使用Vue.js,Vuex,Express,MongoDB检索currentUser数据 [英] How to retrieve currentUser data with Vue.js, Vuex, Express, MongoDB
问题描述
我正在尝试构建一个MEVN堆栈身份验证页面,该页面返回有关当前登录用户的信息.登录后,路由器会将用户名
作为道具传递给Home.vue,同时重定向到Home.vue.
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方法
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>
然后在Home.vue组件中调度Vuex动作,该组件将用户名传递给store.js中的动作处理程序
A Vuex action is then dispatched in the Home.vue component, which passes the username to an action handler in store.js
Home.vue中的实例
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)
}
}
})
商店从Express路由中请求登录用户的用户名,该Express路由是根据具有 username
作为查询的URL来搜索登录用户的:
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}
快速路线
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>
但是...只要刷新浏览器,用户名就会消失.知道为什么名称不显示在屏幕上吗?它与作为道具传递给Home.vue的用户名有关吗?而不是一直将用户名prop传递给:
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}
...也许还有另一种方式可以将登录用户的用户名作为查询传递给URL?
...is there perhaps another way that I could pass the username of the logged-in user as a query in the URL?
更新后的STORE.JS
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]
})
推荐答案
在Vue/Vuex中,刷新页面或转储缓存后,状态将被清除干净.如果要保留数据,则有几种选择.
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.
- 您可以使用插件: https://github.com/championswimmer/vuex-persist
- 您可以将用户名存储在localStorage中.
- 您可以将信息存储在cookie中.
如果您将它们存储在本地,那么如果您担心用户对本地存储的数据有什么担心,最好使用令牌或其他安全措施.
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.
这篇关于如何使用Vue.js,Vuex,Express,MongoDB检索currentUser数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!