我正在尝试使用Vue.js,Node,Express和MongoDB构建身份验证接口。到目前为止,我已经成功启用了用户注册,使用bcrypt包对密码进行加密时,将姓名,电子邮件和密码推送到MongoDB数据库中。然后,用户在Login.vue
中重新输入电子邮件和密码。由于导航栏控制过渡以反映正在登录,因此登录似乎有效。但是,屏幕内容不会重新路由到Profile.vue
。而是,屏幕保留在Login.vue
上,并且控制台上显示一条错误消息,内容为uncaught (in promise) undefined
。我已将问题缩小到this.$router.push('profile')
中的Login.vue
。 console.log(this.$router.push('profile'))
返回Promise {<rejected>: undefined}
,表示拒绝重新路由到Profile.vue
的承诺。为了解决这个问题,我尝试在router.js
中实现路由守卫的不同变体,我认为这可能与this.$router.push('profile')
中的Login.vue
冲突。关于如何解决路由问题的任何建议?
Login.vue
<template>
<div class="container">
<div class="row">
<div class="col-md-6 mt-5 mx-auto">
<v-form
ref="form"
>
<v-text-field
v-model="email"
label="email"
required
></v-text-field>
<v-text-field
v-model="password"
label="password"
required
:type="show1 ? 'text' : 'password'"
></v-text-field>
<v-btn
class="mr-4"
@click.prevent="login"
>
login
</v-btn>
</v-form>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios'
import EventBus from './EventBus'
export default {
data () {
return {
email: '',
password: '',
show1: false
}
},
methods: {
async login () {
let res = await axios.post('http://localhost:5000/users/login', {
email: this.email,
password: this.password
})
localStorage.setItem('usertoken', res.data)
this.email = ''
this.password = ''
this.emitMethod()
this.$router.push('profile')
},
emitMethod () {
EventBus.$emit('logged-in', 'loggedin')
}
}
}
</script>
router.js
import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/components/Login'
import Register from '@/components/Register'
import Profile from '@/components/Profile'
Vue.use(Router)
const router = new Router({
mode: 'history',
routes: [
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/register',
name: 'Register',
component: Register
},
{
path: '/profile',
name: 'Profile',
component: Profile,
meta: {
requiresAuth: true
}
}
]
})
router.beforeEach((to, from, next) => {
const isLoggedIn = localStorage.getItem('token')
const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
if (requiresAuth && !isLoggedIn) next('login')
else if (!requiresAuth && isLoggedIn) next('profile')
else next()
})
export default router