Axios取消在axios客户端文件中不起作用- reactjs

h7wcgrx3  于 2023-04-06  发布在  iOS
关注(0)|答案(1)|浏览(159)

我已经为API服务创建了一个公共axios请求文件,一个公共函数getRequest(URL)在需要的地方被调用。
我想实现的是,每当新请求被调用/触发时,以前的请求应该被取消。
这是我已经尝试过的,但它并没有像预期的那样工作。

// My component Users.js
async function getUsers(url) {
    try {
        const response = await getRequest(url);
        // further process with the response
    } catch (error){
        // handling error here
    }
}

useEffect( ()=>{
    // URL is getting form endpoints constnats
    getUsers(URL);
},[]);
// --------------- end of my component ---------------
//axiosClient.js
import axios from 'axios';
import { BASEURL } from '../config/endpoints';
import { getToken } from '../Auth';

const CancelToken = axios.CancelToken;

export function getRequest(URL, payload={}, headers={}) {
    return apiRequest(URL, payload, "get", headers);
}

export async function apiRequest(endPoint, data, method, headers, requestOptions = {}) {
    return new Promise(async (resolve, reject) => {
      const token = getToken();
      const headers = {
        Accept: 'application/json',
      };
      
      if (data instanceof FormData) {
        headers['Content-Type'] = 'multipart/form-data';
      } else {
        headers['Content-Type'] = 'application/json';
      }
  
      if (token) {
        headers['access_token'] = token;
      }
  
      axios({
        method: method,
        url: endPoint,
        headers:headers,
        data: data,
        cancelToken: new CancelToken(function executor(c) {return c;})
      }).then((result) => { return resolve(result); }).catch((error) => {return reject(error);});
      return false;
    });
  }
// --------------- end of axios client ----------------
92dk7w1h

92dk7w1h1#

我终于找到了解决办法。

//axiosClient.js

import axios from 'axios';
import { BASEURL } from '../config/endpoints';
import { getToken } from '../Auth';

const CancelToken = axios.CancelToken;
let cancel;

export function getRequest(URL, payload={}, headers={}) {
    return apiRequest(URL, payload, "get", headers);
}

export async function apiRequest(endPoint, data, method, headers, requestOptions = {}) {
    if (cancel !== undefined) cancel();

    return new Promise(async (resolve, reject) => {
      const token = getToken();
      const headers = {
        Accept: 'application/json',
      };
      
      if (data instanceof FormData) {
        headers['Content-Type'] = 'multipart/form-data';
      } else {
        headers['Content-Type'] = 'application/json';
      }
  
      if (token) {
        headers['access_token'] = token;
      }
  
      axios({
        method: method,
        url: endPoint,
        headers:headers,
        data: data,
        cancelToken: new CancelToken(function executor(c) {return c;})
      }).then((result) => { return resolve(result); }).catch((error) => {return reject(error);});
      return false;
    });
  }
// --------------- end of axios client ----------------

相关问题