vue.js 位于中间件中的等待请求在呈现页面之前完成

tcbh2hod  于 2023-10-23  发布在  Vue.js
关注(0)|答案(1)|浏览(160)

我有个问题我使用Vue.js和Nuxt.js。
我做了中间件来实现身份验证。这里我使用JSON Web Token。我有accessKey和refreshKey。refreshKey用于在accessKey过期时请求新的accessKey。因此,在中间件中,我调用向API发出请求的操作。下面是我的代码:
首页/index.vue

<template>
I'm protected resource
</template>

<script>
export default {
  middleware: 'authentication'
}
</script>

middleware/authentication.js

import { isEmpty } from 'lodash'
export default async function({ store, redirect, app }) {
  if (isEmpty(refKey)) {
    //logout
  }
  if (isLogin && !isEmpty(accKey)) {
    // store auth data
  } else if (isLogin && isEmpty(accKey)) {
    // call action that make request with axios to the API
    return await store.dispatch('user/requestNewToken')
  } else {
    return redirect('/')
  }
}

我的行动:

async requestNewToken({ dispatch, commit }) {
    const refreshReq = await dispatch('refreshToken')
    if (!isUndefined(refreshReq) {
      await dispatch('setupAuthCookies')
      return refreshReq
    }
  },

但应用程序返回错误。这是因为页面在AXIOS请求完成之前呈现。如何防止Vue在我的axios请求(获取新的accessKey)完全完成之前重定向和渲染页面?谢谢.

oalqel3c

oalqel3c1#

你必须先注册你的商店,然后获得用户信息/权限等,然后你必须注册路由等,然后我会工作得很好:)

/**
 * Next, we will create a fresh Vue application instance. You may then begin
 * registering components with the application instance so they are ready
 * to use in your application's views. An example is included for you.
 */
axios.defaults.headers.common['Authorization'] = `Bearer ${ localStorage.getItem('auth_token') }`;
app.use(createPinia());
// getting user form token
const authStore = useAuthStore();
await authStore.getUser(localStorage.getItem('auth_token'));

import App from './App.vue';

app.use(Router);
app.component('app', App);

相关问题