[英]How to clone an axios instance
我有一个全局 axios 实例,我在我的应用程序中使用它。 我想针对特定请求在本地更新标头。 但是标题更新正在更新全局默认值。 我想了解执行此操作的最佳方法。 目前我正在设法重置标题。 还玩弄了深度克隆全局 axios 实例的想法。 它只是感觉像是一个重要的功能,但找不到任何文档,除了 github 问题谈论子实例。 ( https://github.com/axios/axios/issues/1170 )
编辑:抱歉没有提供代码。 这是我给出一个想法的设置:以下是我的全局 axiosClient(在文件apiClient.js
中),添加了一些拦截器(代码中未显示)。
const axiosClient = axios.create({
baseURL,
headers: {
Authorization: <bearer_token>,
'Content-Type': 'application/json',
.
}
});
在我的模块中,我导入相同的客户端来发出 api 请求,如下所示:
import axiosClient from '../apiClient';
export function someRequest({ file }) {
let formData = new FormData();
formData.append('file', file);
const initHeader = axiosClient.defaults.headers['Content-Type'];
axiosClient.defaults.headers['Content-Type'] = 'multipart/form-data'; // I want to make this change only for the local instance
const request = axiosClient.post('parse-rebalance-data', formData);
axiosClient.defaults.headers['Content-Type'] = initHeader; //I have to reset the changes I made to the axiosClient
return request;
}
现在我的问题又是,(1) 我是否需要以这种 hacky 的方式来做,或者 (2) 我应该研究深度克隆本地副本,或者 (3) 是否有记录的方法来做这件事,我错过了.
Axios 实例所做的所有事情都是为配置设置默认值。 但是,您可以使用config
参数将任何其他配置传递给每个调用,就像使用全局 Axios 一样:
import axiosClient from '../apiClient';
export function someRequest({ file }) {
let formData = new FormData();
formData.append('file', file);
return axiosClient.post('parse-rebalance-data', formData, {headers: {'Content-Type': 'multipart/form-data'}});
}
config
参数中指定的标头与默认值中的标头合并。
你可以这样做:
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
您可以在这里阅读更多内容:
您实际上可以从另一个实例创建一个实例。
因此,例如,您可以:
// src/services/http.js
import axios from 'axios';
const http = axios.create({
headers: {
Accept: 'application/json'
},
withCredentials: true
});
export default http;
然后你需要一个更具体的实例:
// src/services/pouic.js
import http from './services/http';
// Defines common base URL for all services in this module.
const httpPouic = http.create({
baseURL: 'https://pouic.com/api'
});
export default {
getPouic: async function () {
const pouics = await httpPouic({
method: 'get'
url: '/pouic-list'
});
return pouics.data;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.