【问题标题】:How does i get Axios post request is progressing我如何获得 Axios 发布请求正在进行中
【发布时间】:2020-07-11 17:59:19
【问题描述】:

这是我想要实现的简单事情(简单的 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 框架

【问题讨论】:

    标签: javascript ajax laravel axios


    【解决方案1】:

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

    axios.post(path, data, options) 
    

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

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

    【讨论】:

      【解决方案2】:

      这是一个使用 axios 发出 post 请求的工作示例。 每当您在正文中传递数据时,都会触发 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上的例子

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-12-10
        • 1970-01-01
        • 2021-12-25
        • 2021-05-31
        • 1970-01-01
        • 2020-05-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多