gpt4 book ai didi

javascript - Vue.js,将值从组件发送到 router/index.js

转载 作者:行者123 更新时间:2023-12-03 00:32:26 25 4
gpt4 key购买 nike

我正在尝试从 Login.vue 组件发送 JWT token 值,并在 router/index.js 中验证它在我将用户重定向到下一页之前。

登录.vue:

<script>
import axios from "axios";

export default {
name: "Login",
methods: {
login() {

let userDetails = {
'Username' : this.email,
'Password' : this.password
}
axios
.post('https://localhost:44349/api/Token/CreateToken',userDetails)
.then((response) => {
this.token = response.data.token
this.$router.push({
name:'Books',
params:{token:this.token}}) // <--- send Token
})
.catch((error) => {
console.log(error)
});
}
}
};
</script>

路由器/index.js

const router = new Router({    
routes: [
{
path: '/books',
name: 'books',
component: Books,
props: true,
meta: {
requiresAuth: true
}
},
{
path: '/login',
name: 'Login',
component: Login
}
]
});


router.beforeEach((to, form, next) => {
if (to.matched.some(rec => rec.meta.requiresAuth)) {

let isTokenValid= ??; // how to get the token?

if (isTokenValid) {
next();
}
else {
next({ name: 'Login' });
}
}
});

export default router

最佳答案

我使用localstorage来存储 token 。或者,您可以使用 vuex 进行存储,请遵循此 Authentication using Vuex

  .then((response) => {  
this.token = response.data.token
localStorage.setItem('user-token', this.token);
this.$router.push({
name:'Books',
}) // <--- send Token
}).catch(){
localStorage.removeItem('user-token');
}

关于javascript - Vue.js,将值从组件发送到 router/index.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53801040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com