如何先根据后端响应初始化Vue APP? [英] How to initialize the Vue app depending on back-end response first?

查看:47
本文介绍了如何先根据后端响应初始化Vue APP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在应用程序中的任何其他代码之前运行一些代码,这些代码将向后端发送请求,然后更新商店。 我需要先执行这一部分,因为巡回警卫依赖它,如何实现这一点?

代码示例

获取用户信息和设置

async init() {
    await AuthService.initCSRF();
    await AuthService.getUser().then((res) => {
      if (res.data && res.data.user) {
        this.loginLocally(res.data.user);
      } else {
        this.logoutLocally();
      }
    });
}

身份验证防护

export function isLoggedIn(to, from, next) {
  console.log('Checked', store.state.auth.isLoggedIn);
  if (store.state.auth.isLoggedIn) {
    next();
    return;
  }

  next({ name: 'login' })
}

推荐答案

在我的旧项目中,我做了这样的事情。希望您有所了解。

app.js

import App from './components/App.vue'
store.dispatch('auth/attempt', sessionStorage.getItem('token')).then(() =>{
new Vue({
    el: '#app',
    router,
    store,
    render: h => h(App),
 });
});

在这里,我在呈现应用程序之前验证保存在本地存储中的令牌。

我的Vuex操作类似于此

async signIn({dispatch}, credentials) {
  let response = await axios.post("auth/signin", credentials);
  await dispatch('attempt', response.data.token)
},


async attempt({commit, state}, token) {
  if (token) {
    await commit('SET_TOKEN', token);

  }
  if (!state.token) {
    return;
  }

  try {
    let response = await axios.get('auth/me');
    commit('SET_USER', response.data)
  } catch (e) {
    commit('SET_TOKEN', null);
    commit('SET_USER', null);
  }
},
async signOut({commit}) {
  axios.post('auth/signout').then(() => {
    commit('SET_TOKEN', null);
    commit('SET_USER', null);
  });
}

我正在使用订阅者侦听突变并在请求标头中添加或删除令牌

import store from '../store'

store.subscribe((mutation) => {

 if (mutation.type === 'auth/SET_TOKEN') {
  if (mutation.payload) {
   axios.defaults.headers.common['Authorization'] = `Bearer ${mutation.payload}`;
  sessionStorage.setItem('token', mutation.payload);
} else {
  axios.defaults.headers.common['Authorization'] = null;
  sessionStorage.removeItem('token');
  }
 }
});

最后一个用于处理令牌过期的AXIOS拦截器。

import router from '../plugins/router'
import store from '../store'
import axios from "axios";

axios.interceptors.response.use((response) => {

  return response;
}, (error) => {
if (error.response.status) {
  if (error.response.status === 401) {

  if (router.currentRoute.name !== 'landing') {
    store.dispatch('auth/clearToken').then(() => {
      router.replace({
        name: 'landing'
      });

    }).finally(() => {
      swal.fire(
        'Your Session is Expired',
        'Please sign in again!',
        'error'
      )
    });
    }
  }
}

return Promise.reject(error);
});

这篇关于如何先根据后端响应初始化Vue APP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆