Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a "before" callback in axios

I'm writing a project in Vue.js (using axios) with file upload functionality.

I need to implement an action before the POST request is sent in 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 the before callback of course because it isn't an axios option. From the documentation, I know I should use an interceptor to implement hooks before requests are sent. But I can't get around it.

Edit: I'd like to have something similar to Vue's $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);
})
like image 257
Kornel Avatar asked May 14 '17 22:05

Kornel


1 Answers

If you need to call a function before each axios request, you should use an interceptor.

In your case:

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

axios.post('/upload', form, { ... });
like image 63
thanksd Avatar answered Oct 21 '22 18:10

thanksd