【问题标题】:How to use dynamic auth-header in axios(vue.js)?如何在 axios(vue.js) 中使用动态 auth-header?
【发布时间】:2019-12-28 16:39:28
【问题描述】:

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

//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 存储的身份验证令牌并将其设置在服务中。

我会像这样使用这项服务:

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

情况是,auth key 时不时地变化,所以我有一个设置会更新 store 中的 auth key。 设置成功更新store中的auth key,但是api-client.js中的key没有更新。它只加载一次,并且商店中的更新不会级联到这个api-client.js

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

【问题讨论】:

  • 我建议在每个请求之前添加标头(在某种类似的中间件中)。这样你总是会为每个请求提取最新的令牌。
  • 我想实现在一个地方配置身份验证密钥并在任何地方使用它的能力。如果我必须在标题中包含密钥,那将无法达到目的。
  • 请查看 axios 文档中的请求拦截器。基本上,您将所有内容都放在一个地方(拦截器),只需将您的令牌附加到每个请求都会发生的当前标头上。因为我现在在手机上,所以我回家后可以发布一个代码示例。

标签: javascript vue.js axios vuex


【解决方案1】:

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

//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的最新版本;

【讨论】:

    猜你喜欢
    • 2020-01-20
    • 2021-11-17
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 2018-11-01
    • 2018-08-05
    • 2020-04-12
    • 2019-01-06
    相关资源
    最近更新 更多