如何在axios中实现“before”回调

时间:2017-05-14 22:15:39

标签: javascript vuejs2 axios

我正在axios(使用POST)编写一个带有文件上传功能的项目。

我需要在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... }); 请求之前实施操作:

before

当然,除了axios回调之外,一切都有效,因为它不是$http选项。从文档中,我知道在发送请求之前我应该​​使用拦截器来实现钩子。但我无法解决它。

修改 我想要一些类似于Vue的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); })

\"[0-9]{4}-[0-9]{2}-[0-9]{2}\"\^\^[^ ]*

1 个答案:

答案 0 :(得分:18)

如果您需要在每个axios请求之前调用函数,则应使用interceptor

在你的情况下:

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

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