如何在axios中编写此xhr请求?

时间:2019-12-15 03:21:27

标签: javascript axios

如何使用Axios调用而不是XMLHttpRequest编写以下代码?

var xhr = new XMLHttpRequest;
xhr.open("POST", "/attachments", true);
/*open an ajax request.*/

xhr.upload.onprogress = function(event) {
  var progress = event.loaded / event.total * 100;
  attachment.setUploadProgress(progress);
};

xhr.onload = function() {
  if (xhr.status === 201) {
    setTimeout(function() {
      var url = xhr.responseText;
      attachment.setAttributes({ url: url, href: url });
    }, 30)
  }
};

attachment.setUploadProgress(10);

setTimeout(function() {
  xhr.send(attachment.file);
}, 30)

1 个答案:

答案 0 :(得分:2)

原始XHR函数调用的分解:

  1. POST-将文件传输到/attachments端点

  2. async参数设置为true

  3. 设置一个progress事件处理程序

  4. 设置一个load事件处理程序,用于检查201状态代码

Axios等效项:

  1. Axios为POST数据提供以下API:

  2. Axios呼叫默认为async,因此无需设置标志。

  3. Axios调用的config参数采用一种onUploadProgress回调方法来跟踪文件上载的进度。

  4. Axios调用(Promise)的响应固有地指示load事件。响应还包含response.status中的HTTP状态代码。

总而言之,代码翻译将与此类似:

import axios from 'axios'

let attachment = /*...*/

async function postAttachment(file) {
  const config = {
    onUploadProgress(progressEvent) {
      const progress = progressEvent.loaded / progressEvent.total * 100
      attachment.setUploadProgress(progress)
    }
  }

  const response = await axios.post('/attachments', file, config)

  if (response.status === 201) {
    setTimeout(() => {
      const url = response.data
      attachment.setAttributes({ url, href: url })
    }, 30)
  }
}

setTimeout(() => {
  postAttachment(attachment.file);
}, 30)