首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何用axios编写这个xhr请求?

如何用axios编写这个xhr请求?
EN

Stack Overflow用户
提问于 2019-12-15 03:21:27
回答 1查看 6.4K关注 0票数 3

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

代码语言:javascript
运行
复制
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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-15 09:48:43

原始XHR函数调用的分解:

将文件设置为

  1. POST-ing endpoint
  2. async参数为true
  3. Sets a progress-event处理程序
  4. 设置一个load-event处理程序,以检查201状态代码

Axios对应物:

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

代码语言:javascript
运行
复制
- [`axios.post(url[, data, [config]])`](https://github.com/axios/axios#axiosposturl-data-config)
- [`axios({ url, method: 'POST' })`](https://github.com/axios/axios#axiosconfig)
- [`axios.request({ url, method: 'POST' })`](https://github.com/axios/axios#axiosrequestconfig)

  1. Axios调用默认情况下是async,因此不需要设置标志。
  2. Axios调用的config参数采用onUploadProgress回调方法来跟踪文件上载的进度。
  3. Axios调用的响应( Promise)固有地指示一个load事件。响应还包含response.status.

中的HTTP代码

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

代码语言:javascript
运行
复制
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)
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59340977

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档