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);
})
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, { ... });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With