我正在使用 Vue.js
(使用 axios
)编写一个具有文件上传功能的项目。
我需要在 axios
中发送 POST
请求之前执行一个操作:
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
选项。从文档中,我知道我应该在发送请求之前使用拦截器来实现 Hook 。但我无法绕过它。
编辑:
我想要类似于 Vue 的 $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);
})
最佳答案
如果你需要在每次 axios 请求之前调用一个函数,你应该使用 interceptor .
在你的情况下:
axios.interceptors.request.use((config) => {
fileObject.xhr = config;
return config;
});
axios.post('/upload', form, { ... });
关于javascript - 如何在axios中实现 "before"回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43969324/