如何使用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)
答案 0 :(得分:2)
原始XHR函数调用的分解:
POST
-将文件传输到/attachments
端点
async
参数设置为true
设置一个progress
事件处理程序
设置一个load
事件处理程序,用于检查201
状态代码
Axios等效项:
Axios为POST
数据提供以下API:
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)