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

标签 javascript vuejs2 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...
});

当然,除了 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/

相关文章:

javascript - AJAX获取对象并将json字符串数据与当前值进行比较

javascript - 如何在异步回调中捕获局部变量值

javascript - ReactJS:如何让<div/> float 不影响下一个<div/>?

javascript - Vue Actions 中的菊花链式 promise 会导致无限循环

laravel-5 - 错误类型错误 : Cannot read property 'dispatch' of undefined at app. js:12012

javascript - 如何将 AngularJS 应用程序连接到 Kinvey?

vue.js - 如何在 Nuxt 2 和 3 中获取当前路由名称?

javascript - 在 Vue 应用程序中模拟 axios 以进行前端测试

node.js - vuejs 2 axios 放置,删除

reactjs - axios.delete(url[,config]) : Type has no properties in common with type 'AxiosRequestConfig'