function SendRequest(method, url, data, bearerToken) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log('readyState');
console.log(this.responseText);
}
});
xhr.open(method, rootPath + url);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("cache-control", "no-cache");
if (typeof (bearerToken) != 'undefined') {
xhr.setRequestHeader("Authorization", "Bearer " + bearerToken);
}
xhr.onload = function () {
if (xhr.status == 200) {
resolve(xhr.response);
}
else {
reject(Error(xhr.statusText));
}
};
xhr.onerror = function () {
reject(Error("Network Error"));
};
if (typeof (data) != 'undefined') {
xhr.send(JSON.stringify(data));
} else{
xhr.send();
}
});
}
为了异步执行,先定义个Promise
var token = new Token();
token.load();
token.requestToken('zhaoma', '1029824zzZ').then((data) => {
var resp = JSON.parse(data);
console.log('request token');
console.log(resp);
token.setToken(resp.token);
token.setExpire(resp.expireTime);
token.save();
});
?
|