How to implement a do callback in axios

I am writing a project in Vue.js(using axios) with the ability to upload files.

I need to perform an action before the request is POSTsent to axios:

axios.post('/upload', form, {
  before: (xhr) => {
    fileObject.xhr = xhr;
  },
  onUploadProgress: (e) => {
    //emit progress event etc...
    console.log('upload progress: ' + e.loaded);
  }
}).then((response) => {
  console.log('finished...');
  //emit finished event etc...
}, () => {
  console.log('error...');
  //emit failed event etc...
});

Everything works, except for the callback before, of course, because it is not a parameter axios. From the documentation, I know that I should use an interceptor to implement intercepts before sending requests. But I can't get around this.

Edit: I would like to have something similar to Vue $http:

this.$http.post('/upload', form, {
  before: (xhr) => {
    fileObject.xhr = xhr;
    //maybe do something else here
  },
  progress: (e) => {
    eventHub.$emit('progress', fileObject, e);
  }
}).then((response) => {
  eventHub.$emit('finished', fileObject);
}, () => {
  eventHub.$emit('failed', fileObject);
})
+6
source share
1 answer

axios, interceptor.

:

axios.interceptors.request.use((config) => {
  fileObject.xhr = config;
  return config;
});

axios.post('/upload', form, { ... });
+9

Source: https://habr.com/ru/post/1017253/


All Articles