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

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...