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

前端之家收集整理的这篇文章主要介绍了javascript – 如何在axios中实现“之前”回调前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用文件上传功能在Vue.js(使用axios)编写项目.

我需要在axios中发送POST请求之前实现一个动作:

  1. axios.post('/upload',form,{
  2. before: (xhr) => {
  3. fileObject.xhr = xhr;
  4. },onUploadProgress: (e) => {
  5. //emit progress event etc...
  6. console.log('upload progress: ' + e.loaded);
  7. }
  8. }).then((response) => {
  9. console.log('finished...');
  10. //emit finished event etc...
  11. },() => {
  12. console.log('error...');
  13. //emit Failed event etc...
  14. });

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

编辑:
我想要一些类似于Vue的$http:

  1. this.$http.post('/upload',{
  2. before: (xhr) => {
  3. fileObject.xhr = xhr;
  4. //maybe do something else here
  5. },progress: (e) => {
  6. eventHub.$emit('progress',fileObject,e);
  7. }
  8. }).then((response) => {
  9. eventHub.$emit('finished',fileObject);
  10. },() => {
  11. eventHub.$emit('Failed',fileObject);
  12. })

解决方法

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

在你的情况下:

  1. axios.interceptors.request.use((config) => {
  2. fileObject.xhr = config;
  3. return config;
  4. });
  5.  
  6. axios.post('/upload',{ ... });

猜你在找的JavaScript相关文章