如何在axios(vue.js)中使用动态身份验证头?

6

我正在构建一个依赖于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
  }
})

现在请注意,我正在使用getter从vuex store中获取auth token,并将其设置在服务中。

我将像这样使用此服务:

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

情况是,授权密钥会不时更改,因此我有一个设置可以更新存储中的授权密钥。 该设置成功地在存储中更新了授权密钥,但是api-client.js中的密钥没有被更新。它只加载一次,存储中的更新未级联到此 api-client.js 中。

是否有解决此问题的模式?请建议。


我建议在每个请求之前添加头信息(在某种中间件或类似的东西中)。这样,您每次请求时都会获取最新的令牌。 - zhuber
我想要实现在单个位置配置认证密钥并在任何地方使用的能力。如果我必须将密钥包含在标头中,那就没有达到目的。 - spark
2
请查看axios文档中有关请求拦截器的内容。基本上,您可以将所有内容放在一个地方(拦截器)并仅将您的令牌附加到当前标头中,这将发生在每个请求中。我现在正在使用移动设备,一旦回家,我可以发布一个代码示例。 - zhuber
1个回答

15

由于您的令牌是动态的,因此无法在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;

这样,拦截器函数会在每个请求上发生,并会获取您的authKey的最新版本。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接