Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
170
rated 0 times [  177] [ 7]  / answers: 1 / hits: 37268  / 7 Years ago, sun, may 14, 2017, 12:00:00

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

More From » vuejs2

 Answers
6

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, { ... });

[#57788] Friday, May 12, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
longd

Total Points: 616
Total Questions: 110
Total Answers: 101

Location: Andorra
Member since Sat, May 27, 2023
1 Year ago
;