如何使用 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)
原始 XHR 函数调用分解:
POST
- 将文件发送到 /attachments
端点
async
参数设置为 true
设置一个progress
-事件处理器
设置一个 load
事件处理程序来检查 201
状态代码
Axios 等价物:
Axios 提供了以下 API 来POST
数据:
Axios 调用默认是async
,所以不需要设置标志。
Axios 调用的config
参数采用onUploadProgress
。跟踪文件上传进度的回调方法。
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)