How to implement a "before" callback in axios

29,393

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, { ... });
Share:
29,393
Kornel
Author by

Kornel

Linux user and administrator. PHP programmer. Favourite framework - Laravel.

Updated on February 08, 2020

Comments

  • Kornel
    Kornel over 4 years

    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);
    })