Vue.js & Vuex - 将访问令牌存储在商店中,并将用户重定向到登录的URL



>我正在尝试将访问令牌存储到 createStore (index.js( 中,然后在用户登录后重定向到另一个网页。

为此,我需要在突变中创建突变.js以便我可以设置访问令牌并设置刷新令牌。刷新应该类似于时间戳。

test.vue 是用于验证用户的登录代码。

所以,基本上我需要创建一个函数,设置访问令牌,设置refrefresh令牌,然后在用户按下登录按钮后将用户重定向到另一个网页。

提前非常感谢!

索引.js:

import vuex from 'vuex';
import mutations from './mutations';
const createStore = () =>{
return new vuex.Store({
state: {
accessToken: "halo",
access_token: response.data.access_token,
refresh: response.data.refresh_token
},
getters:{
accessToken(state, getters){
return state.accessToken;
}
},
mutations
});
};
export default createStore;

突变.js:

const mutations = {
setToken(state, token) {
state.accessToken = token;
}
}
export default mutations;

test.vue:

<template>
<form>
<div class="login">
<div>
<input name="email" type="text" v-model="email" v-validate="'required'" placeholder="Email" class="eSection" id="email">
<p v-show="wrong.email">
Email is missing or incorrect. Please try again!
</p>
<i name="emailFormat" type="text" v-validate="'required|emailFormat'" placeholder="Email" class="eSection" id="email"></i>
<p v-show="wrong.emailFormat">
Not valid email!
</p>
<input name="password" type="password" v-model="password" v-validate="'required'" placeholder="Password" class="pSection"
id="password">
<p v-show="wrong.password">
Password is missing or incorrect. Please try again!
</p>
<p v-show="wrong.all">
Login Details Incorrect!
</p>
<button type="button" class="log" @click="login">LogIn</button>
</div>
</div>
</form>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
email: "test@gmail.com",
password: "123456",
flag: false,
wrong: {
email: false,
emailFormat: false,
password: false,
all: false
},
}
},
methods: {
login: function (index) {
this.wrong.email = false;
this.wrong.password = false;
this.wrong.all = false;
this.wrong.emailFormat = false;
axios.post(`https://api.ticket.co/auth/login`, {
email: this.email,
password: this.password
})
.then(response => {
// JSON responses are automatically parsed.
console.log(response.data)
console.log(response.status)
})
.catch(e => {
console.log(e)
console.log(e.response.status)
var vueObject = this
switch (e.response.status) {
case 400:
if (!vueObject.email) {
console.log(1)
this.wrong.email = true;
} else if (!vueObject.emailFormat) {
console.log(2)
this.wrong.emailFormat = true;
};
if (!vueObject.password) {
console.log(3)
this.wrong.password = true;
}
break;
case 401:
console.log(4)
this.wrong.all = true;
break;
}
})
},
},
}
</script>

我认为这个问题有两种可能的解决方案。

  • 第一:你可以使用 vue-router。在这种情况下,将没有 页面刷新,只是组件更改。这样直到你刷新 页面,每个 Vuex 状态都将存在。(但它不是最好的 解决方案(。
  • 第二;你可以写一个休息电话,什么是给你实际的回报 用户令牌(如果用户已通过身份验证(。所以只有这个 rest api 调用使用 会话身份验证和/或CSRF令牌(如果您,请查看wiki 不知道(。如果你使用axios,最优雅的方式之一拦截器(在每个 axios 调用之前运行(,如果 用户已经过身份验证。查看此 github 评论以获取更多内容 信息。(确保会话超时比令牌长 终身:) (

最新更新