我想声明 2 个 axios 实例,因此 1 个用于使用 access_token
进行 API 调用,另外 1 个用于使用 refresh_token
。
所以我有这样的代码:
config.js
import axios from 'axios';
const axiosAccessClient =function () {
const defaultOptions = {
baseURL: 'my_url',
headers: {
'Content-Type': 'application/json',
}
};
let instance = axios.create(defaultOptions);
instance.interceptors.request.use(function (config) {
const token = localStorage.getItem('access_token');
config.headers.Authorization = token ? `Bearer ${token}` : '';
return config;
});
return instance;
};
const axiosRefreshClient =function () {
const defaultOptions = {
baseURL: 'my_url',
headers: {
'Content-Type': 'application/json',
}
};
let instance = axios.create(defaultOptions);
instance.interceptors.request.use(function (config) {
const token = localStorage.getItem('refresh_token');
config.headers.Authorization = token ? `Bearer ${token}` : '';
return config;
});
return instance;
};
export {
axiosAccessClient,
axiosRefreshClient
}
所以在我的 Request.js 中我做了这样的事情:
import {axiosAccessClient,axiosRefreshClient} from "./config";
static async access(url,body) {
return await axiosAccessClient.post(url, body)
.then(function (response) {
return response;
}).catch(function (error) {
throw error;
})
}
static async refresh(url,body){
return await axiosRefreshClient.post(url, body)
.then(function (response) {
return response;
}).catch(function (error) {
throw error;
})
}
但是当我运行应用程序时,它在 Request.js
中的 access()
处崩溃,显示此错误:
_AxiosConfig__WEBPACK_IMPORTED_MODULE_2__.axiosAccessClient.post is not a function
但是如果我执行以下操作:
在
,config.js
中导出默认的axiosAccessClient()
从
Request.js
中的“./config”导入axiosAccessClient
然后代码工作了(这很奇怪),但是这样我无法从 Request.js
中的 refresh()
访问 axiosRefreshClient
问题:
有人可以告诉我为什么会发生这种情况吗?我读了所有这个例子,但仍然无法弄清楚:
如何解决这个问题?从单个文件导出多个函数
最佳答案
您的 config.js
导出函数;您需要重写它,以便它导出函数调用的结果,即实例。
// change name of functions
function generateAccessClient() {
..
}
// create instances
const axiosAccessClient = generateAccessClient();
const axiosRefreshClient = generateRefreshClient();
// export them
export {
axiosAccessClient,
axiosRefreshClient
}
这样您就可以导入两者。使用 default
导出与您的问题无关,您只是不小心通过在末尾添加 ()
解决了它。
另一种方法是这样做:
const axiosAccessClient = (function () {
...
})();
与axiosRefreshClient
相同。
现在您的原始代码就可以工作了。
关于javascript - 如何为不同的承载 token 声明2个axios实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59478624/