微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 如何在axios中实现“之前”回调

我正在使用文件上传功能在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',{ ... });

原文地址:https://www.jb51.cc/js/157742.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐