javascript - 登录后 Vue 应用程序不使用本地存储(vue 路由器)

标签 javascript vue.js vuejs2

当我将用户 key 存储在本地存储中并在成功登录后将用户重定向到仪表板时,我的应用程序直到刷新后才使用存储的 key 。

这是设置 key 的代码。

    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()
})

这可能是什么原因造成的?

最佳答案

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

我改为执行以下操作:

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)
)

像魅力一样工作。

关于javascript - 登录后 Vue 应用程序不使用本地存储(vue 路由器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49463032/

相关文章:

javascript - 从 React-Native 应用程序中的另一个类访问静态变量?

javascript - 没有jquery的无限滚动?

javascript - 如何模糊除当前悬停在CSS中的所有图像

vue.js - 在 vuetify 中打开对话框时将数据分配给字段

eloquent - Vue 2 Laravel 5.3 Eloquent 无法从对象检索数据

vue.js - 我的 Vue.js 代码应该有多个小实例还是一个大实例?

javascript - VueJS在选择相同文件时重新读取文件输入

vue.js - 对 vue 组件进行子类化

javascript - jQuery slideDown 不流畅

vue.js - 使用 laravel mix 混淆代码