如何在axios中实现"before"回调

Kor*_*nel 12 javascript axios vuejs2

我正在Vue.js使用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...
});
Run Code Online (Sandbox Code Playgroud)

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

编辑: 我想要有类似于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);
})
Run Code Online (Sandbox Code Playgroud)

tha*_*ksd 21

如果需要在每个axios请求之前调用函数,则应使用拦截器.

在你的情况下:

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

axios.post('/upload', form, { ... });
Run Code Online (Sandbox Code Playgroud)

  • 我应用了它。但它是多个运行此功能 (2认同)