在Axios Instance类中取消请求

问题描述 投票:0回答:1

我正在使用Redux-(saga)和一个轮询功能。我需要每1秒做一次请求。当我没有收到来自端点的响应时,我需要做一个新的请求。在这种情况下,我认为我需要取消先前的请求并对api端点进行新的xhr尝试。

我的所有请求都是使用Axios客户端完成的。我有一个班级,我将所有api电话分开。我尝试过多个例子(见下面的代码)。然后我调用cancelRequest函数。

有人可以帮助我找到正确的方向吗?

看看这些问题和axios文档,但没有那些可以帮助我:(

Cant cancel Axios post request via CancelToken https://redux-resource.js.org/recipes/canceling-requests

import { getCookie } from '......';

const CancelToken = Axios.CancelToken;
let cancel;

/**
 * Create a single axios client for the 
 * @type {AxiosInstance}
 */
const apiClient = apiUrl =>
  Axios.create({
    baseURL: apiUrl,
    cancelToken: new CancelToken(function executor(c) {
      // An executor function receives a cancel function as a parameter
      cancel = c;
    }),
  });

/**
 * The Api is initialised with a Axios client.
 */
class PinResetApi {
  constructor(client) {
    this.client = client;
  }

  /**
   * Reset pin controller
   */
  requestChangePin = () =>
    this.client(......url).request({
      method: 'GET',
      headers: {
        ...
      },
    });

  /**
   * Cancel reset pin API
   */
  cancelRequest = () => this.client.cancel();

  /**
   * Reset pin status controller
   * @param
   */
  requestChangePinStatus = transactionId =>
    this.client(.....url).request({
      method: 'GET',
      headers: {
        ...
      },

    });
}

const _api = new PinResetApi(apiClient);

export default _api;
export { PinResetApi };
javascript reactjs redux axios es6-class
1个回答
0
投票

您在创建axios实例时尝试添加令牌,但每次发送请求时都需要创建和更新令牌。您可以像这样更新apiClient包装:

// ../services.js

const apiClient = baseURL => {
  const axiosInst = axios.create({
    baseURL,
  });

  axiosInst.defaults.headers.common['Content-Type'] = 'application/json';
  
  return (type = 'get') => {
    let call = null;
    return (url, data, config) => {
      if (call) {
        call.cancel('Only one request allowed!');
      }
      call = axios.CancelToken.source();
      const extConf = {
        cancelToken: call.token,
        ...config,
      };
      switch (type) {
        case 'request':
          return api[type](extConf);

        case 'get':
        case 'delete':
        case 'head':
          return api[type](url, extConf);

        default:
          return api[type](url, data, extConf);
      }
    };
  };
}

export const baseApi = apiClient('http://localhost:5000/api/')

然后像这样使用它:

class PinResetApi {
  constructor(client) {
    this.client = client('request');
  }

  /**
  * Reset pin controller
  */
  requestChangePin = () =>
    this.client({
      method: 'GET',
      headers: {
      ...
    }),
});
© www.soinside.com 2019 - 2024. All rights reserved.