gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 10:18:52 25 4
gpt4 key购买 nike

我正在构建一个严重依赖 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 存储的身份验证 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>

情况是,身份验证 key 不时更改,因此我有一个设置可以更新商店中的身份验证 key 。
设置成功更新存储中的auth key ,但 key 在 api-client.js 没有更新。它只加载一次并且商店中的更新不会级联到这个 api-client.js .

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

最佳答案

由于您的 token 是动态的,因此您无法在 axios 实例工厂 header 设置中定义它。全局处理此问题的最佳方法是使用请求 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 的最新版本。 ;

关于javascript - 如何在 axios(vue.js) 中使用动态 auth-header?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57624855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com