我正在使用文件上传功能在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...
- });
当然,除了之前的回调之外,一切都有效,因为它不是axios选项.从文档中,我知道在发送请求之前我应该使用拦截器来实现钩子.但我无法解决它.
编辑:
我想要一些类似于Vue的$http:
- this.$http.post('/upload',{
- 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',{ ... });