如何在 axios(vue.js) 中使用动态 auth-header?

spa*_*ark 3 javascript vue.js axios vuex

我正在构建一个严重依赖 api 调用的 Vue.js 应用程序。我正在使用 axios 拨打电话。我正在使用与此类似的模式。基本上我已经创建了一个将由所有组件共享的服务。以下是服务:

//api-client.js

import axios from 'axios'
import store from '../src/store'

let authKey = store.getters.getAuthKey
export default  axios.create({
  withCredentials: false, // This is the default
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    authorization: "Basic "+authKey
  }
})
Run Code Online (Sandbox Code Playgroud)

现在请注意,我正在使用 getter 获取 vuex 存储的身份验证令牌并将其设置在服务中。

我将使用此服务,例如:

//App.vue
<template>
    <div>
       <!-- some code -->
    </div>
</template>

<script>
import apiClient from "../api-client.js" 
    export default {
        mounted(){
         apiClient.get("#url").then(()={
            // Do Something

         })
      }
    }
</script>

<style lang="scss">

</style>
Run Code Online (Sandbox Code Playgroud)

情况是,身份验证密钥不时更改,因此我有一个设置可以更新商店中的身份验证密钥。该设置成功更新了 store 中的 auth 密钥,但未更新api-client.js 中的密钥。它只加载一次,商店中的更新不会级联到这个api-client.js

有什么模式可以解决这个问题吗?请建议。

zhu*_*ber 10

由于您的令牌是动态的,因此您无法在 axios 实例工厂标头设置中定义它。全局处理此问题的最佳方法是使用请求拦截器

//api-client.js

import axios from 'axios'
import store from '../src/store'

const apiClient = axios.create({
    withCredentials: false, // This is the default
    headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json'
    }
});

apiClient.interceptors.request.use(function (config) {
    // Do something before request is sent
    let authKey = store.getters.getAuthKey
    config.headers["Authorization"] = "Basic " + authKey;
    return config;
});

export default apiClient;
Run Code Online (Sandbox Code Playgroud)

这样拦截器功能会在每个请求上发生,并会选择最新版本的authKey;