我这里有一个问题。我将 Vue.js 与 Nuxt.js 一起使用。
我制作了中间件来实现身份验证。这里我使用 JSON Web Token。我有accessKey和refreshKey。其中refreshKey用于当accessKey过期时,请求新的accessKey。因此,在中间件中,我调用向 API 发出请求的操作。这是我的代码:
home/index.vue
<template>
I'm protected resource
</template>
<script>
export default {
middleware: 'authentication'
}
</script>
中间件/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)完全完成之前重定向和渲染页面?谢谢。
你必须先注册你的商店,然后获取用户信息/权限等,然后你必须注册路线等,然后我就可以正常工作了:)
/**
* 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('rpm_token') }`;
app.use(createPinia());
// getting user form token
const authStore = useAuthStore();
await authStore.getUser(localStorage.getItem('rpm_token'));
import App from './App.vue';
app.use(Router);
app.component('app', App);