Home > Back-end >  AbortController is not working in ajax and vue.js
AbortController is not working in ajax and vue.js

Time:08-04

I want to cancel the API when I leave the page, but it is not work in AbortController, here is my code snippet

import { fetchSingleList } from '@/api/scada'
data() {
  return {
    abortController: new AbortController()
  }
}
beforeDestroy() {
  this.abortController.abort()
},
methods: {
  getData(){
    fetchSingleList(data, { signal: this.abortController.signal }).then(res => ())
  }
}

here is the fetchSingleList function

export function fetchSingleList(data) {
  return request({
    url: 'api/scada/report',
    method: 'post',
    data
  });
}

and the request function is from axios interceptors

service.interceptors.request.use(
  config => {
    return config;
  },
  error => {
    // Do something with request error
    console.log(error); // for debug
    Promise.reject(error);
  }
);
service.interceptors.response.use(
  response => {
    return response.data;
  },
  error => {
    let message = error.message;
    if (error.response.data && error.response.data.errors) {
      message = error.response.data.errors;
    } else if (error.response.data && error.response.data.error) {
      message = error.response.data.error;
    }
    return Promise.reject(error);
  }
);

my axios version is ^0.22.0

CodePudding user response:

In the fetchSingleList, you need to combine the data and signal in one object, as you have just one parameter.

  getData(){
    fetchSingleList({ data, signal: this.abortController.signal }).then(res => ())
  }

CodePudding user response:

I found my data is in config.data, so I modify my code in axios interceptors, and it works!

here is the code

axios interceptors

service.interceptors.request.use(config => {
  let cfg = {...config}
    if (config.data && config.data.data) {
      cfg = {
        ...config,
        data: config.data.data,
        signal: config.data.signal
      }
    }
    console.log(cfg)
    return cfg;
})

api(vue SFC)

fetchSingleList({ data: data, signal: this.abortController.signal }).then(res => {})
  • Related