簡體   English   中英

如何克隆 axios 實例

[英]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'}
});

您可以在這里閱讀更多內容:

https://axios-http.com/docs/instance

您實際上可以從另一個實例創建一個實例。

因此,例如,您可以:

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM