javascript - 如何使用 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]
})
解决方案
在 Vue/Vuex 中,一旦刷新页面或转储缓存,状态就会被清除。如果你想持久化数据,你有几个选择。
- 您可以使用插件: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.
推荐阅读
- accessibility-insights - 在“链接目的”部分,不应该引用 WCAG SC 2.5.3 吗?
- c++ - 对象实例化后 Esp8266 崩溃
- c - 从微控制器的 I2C 总线读取长寄存器数据
- java - From where the JButton was pressed
- google-bigquery - BigQuery 将 int64 转换为 uint64
- stata - 选择数据集中的多个选择
- python-3.x - 如何解决 Cousera 神经网络分配中与 scipy imread 和 imresize 相关的属性错误?
- appkit - 为什么 enterFullScreenMode 会导致拖放失败?
- sorting - 由于输入无效,无法使用 bcftools 对 VCF 进行排序
- visual-studio - 如何使用 CLI 还原 NuGet 包?