繁体   English   中英

我如何获得 Axios 帖子请求正在进行中

[英]How does i get Axios post request is progressing

这是我想要实现的简单事情(简单的 Ajax 请求。我为此使用了Axios 。)

就像当用户点击一个按钮时,一个 ajax 请求被触发,同时请求正在处理,或者直到它完成我想禁用按钮的请求(或者其他任何东西,比如用户无法与界面交互或向界面显示进度条)用户) 请看代码注释你会明白我真正想说的是什么。

在 Axios 中 get 方法完美运行,请参阅下面的代码

axios.get(url, {
        onDownloadProgress: function (progressEvent) {
            // for get method its working perfectly
            // ajax is processing
            // i can disable the button
        },
        onUploadProgress: function (evt) {
            // this event method never fired
        }
    }).then(res => {
       // ajax is finished
       // i can enable the button again
    })

但是在 post 方法中它不起作用 - 现在我能做些什么

axios.post(url, {
        onDownloadProgress: function (progressEvent) {
            // this event method never fired
        },
        onUploadProgress: function (evt) {
            // this event method never fired
        }
    }).then(res => {
       // ajax is finished
       // i can enable the button again
    })

没有 Axios 它的工作完美

    let xml = new XMLHttpRequest();

    let token = document.querySelector('meta[name="_token"]').getAttribute('content');

    xml.open("POST", "/test");
    xml.setRequestHeader("X-CSRF-TOKEN", token);


    xml.addEventListener('progress', function(evt) {
            // ajax is processing
            // i can disable the button
    });

    xml.addEventListener("load", function(evt){
        // ajax is finished
       // i can enable the button again
    });
    xml.send();

注意:我使用的是laravel框架

这是一个使用 axios 进行发布请求的工作示例。 每当您在正文中传递数据时, onUploadProgress函数就会触发...

axios({
  url: "https://jsonplaceholder.typicode.com/users",
  method: "POST",
  data: {
    username: 'Hello',
    password: 'World'
  },
  onDownloadProgress: function(progressEvent) {
    console.log("___ Document loading ____");
  },
  onUploadProgress: function(evt) {
    console.log('This is the event', evt); // Need to stream
  }
}).then(res => {
  console.log("___ Document loaded ___");
  console.log(res);
});

在这里您可以在CodeSandBox上找到我的示例

您应该通过以下方式使用 axios 中的 post 方法:

axios.post(path, data, options) 

在您的情况下,您正在为 POST 请求传递选项对象而不是数据对象。 解决方案是将空对象作为数据传递,如果您不想随请求发送任何内容:

axios
  .post(
    url,
    {},
    {
      onDownloadProgress: function(progressEvent) {
        // ...
      },
      onUploadProgress: function(evt) {
        // ...
      }
    }
  )
  .then(res => {
    // ...
  });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM