简体   繁体   English

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

[英]How to use dynamic auth-header in axios(vue.js)?

I am building an Vue.js app that relies heavily on api calls. 我正在构建一个严重依赖api调用的Vue.js应用程序。 I am using axios to make call. 我正在使用axios拨打电话。 I am using a pattern similar this . 我正在使用与此类似的模式。 Basically I have created a service that will be shared by all the components. 基本上,我创建了一个将由所有组件共享的服务。 Following is the service: 以下是服务:

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

Now notice I am using a getter to get auth token for the vuex store and seting it in the service. 现在注意,我使用吸气剂来获取vuex存储的身份验证令牌并将其设置在服务中。

I will use this service like: 我将使用此服务,例如:

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

The situation is, auth key changes every now and then, so I have a setting that will update the auth key in the store. 情况是,身份验证密钥有时会更改,因此我有一个设置将更新存储中的身份验证密钥。 The setting updates the auth key in store successfully, but the key in api-client.js is not updated. 该设置成功更新了存储中的auth密钥,但api-client.js中的密钥未更新。 It is loaded only once and the update in the store is not cascaded to this api-client.js . 它仅加载一次,并且存储中的更新不会级联到此api-client.js

Is there any pattern to solve this? 有没有解决的办法? Please suggest. 请提出建议。

Since your token is dynamic, you can't define it in your axios instance factory headers setup. 由于令牌是动态的,因此无法在axios实例工厂标头设置中定义令牌。 Best way to handle this globally is to use 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;

This way interceptor function would occur on each request and would pickup latest version of your authKey ; 这种拦截器功能将在每个请求上发生,并将获取您的authKey最新版本;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM