Vue app登录后不使用localstorage(vue路由器)

时间:2018-03-24 09:11:52

标签: javascript vue.js vuejs2

当我将用户密钥存储在localstorage中并在成功登录后将用户重定向到仪表板时,我的应用程序在刷新之前不使用存储的密钥。

这是设置密钥的代码。

    axios.post(url, creds)
      .then((response) => {
        if (response.data.code === 401) {
          context.error = response.data.data
        } else {
          Vue.ls.set('id_token', response.data.data.key, 60 * 60 * 1000)
          this.user.authenticated = true
        }
      }).catch((err) => {
        context.error = err.data
      })

有趣的是,我在beforeEach中有一个路由保护,这实际上在登录后立即使用了正确的值,而没有刷新。

router.beforeEach((to, from, next) => {
  const r = axios.create({
    baseURL: env.api_url,
    timeout: 25000,
    headers: {
      'Authorization': 'Bearer ' + Vue.ls.get('id_token'),
      'X-Requested-With': 'XMLHttpRequest'
    }
  })

  if (to.name === 'Login') {
    r.get('user').then(() => {
      next({name: 'Dashboard'})
    }).catch(() => {
      next({name: 'Login'})
    })
  }

  if (to.name !== 'Login') {
    r.get('user').then(() => {
      next()
    }).catch(error => {
      console.log(error)
      next({name: 'Login'})
    })
  } else next()
})

导致这种情况的原因是什么?

1 个答案:

答案 0 :(得分:1)

感谢JacobGoh的评论,我设法找到了这个问题。我在main.js文件中创建了axios实例。这是我设置授权标头的地方。当用户登录时,不会更新。

我改为做了以下事情:

router.beforeEach((to, from, next) => {
  if (Vue.ls.get('id_token') === null && to.name !== 'Login' && to.name !== 'Register') {
    router.push('/login')
  } else {
    next()
  }
})

Vue.$http.interceptors.request.use(
  config => {
    config.headers.Authorization = 'Bearer ' + Vue.ls.get('id_token')
    return config
  },
  error => Promise.reject(error)
)

像魅力一样。

相关问题