api - 尝试在Vuejs中通过xhr调用api,使用promise存储响应,不识别.then()
问题描述
我试图通过 xhr 调用 api,因为 axios 不工作,我如何将响应存储在变量中,如果我使用 promise .then() 它会抛出错误,下面是我想要做的
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com', true).then(response=>{
console.log(response);
})
xhr.send();
错误,然后无法读取
解决方案
我得到了答案。它有效!
xhr.onreadystatechange = function() {
var status;
var data;
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate
if (xhr.readyState == 4) { // `DONE`
status = xhr.status;
if (status == 200) {
data = JSON.parse(xhr.responseText);
successHandler && successHandler(data);
} else {
errorHandler && errorHandler(status);
}
}
};