如何使用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)
发布于 2019-12-15 09:48:43
原始XHR函数调用的分解:
将文件设置为
POST
-ing endpointasync
参数为true
progress
-event处理程序load
-event处理程序,以检查201
状态代码Axios对应物:
POST
数据提供了以下API:- [`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)
async
,因此不需要设置标志。config
参数采用onUploadProgress
回调方法来跟踪文件上载的进度。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)
https://stackoverflow.com/questions/59340977
复制相似问题