1.封装请求
export function httpRequest(url, data) {
return new Promise((resolve, reject) => {
const xhr = new plus.net.XMLHttpRequest();
xhr.open("POST", url, true);
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
// 请求成功,返回响应数据
resolve(xhr.responseText);
} else {
// 请求失败,返回错误信息
reject(`HTTP请求失败,状态码:${xhr.status}`);
}
};
xhr.onerror = function() {
// 请求出错,返回错误信息
reject('XMLHttpRequest出错');
};
if (data) {
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(data));
} else {
xhr.send();
}
});
}
2.调用
const postData = {
};
const url= ***;
httpRequest(
url,
postData
)
.then(response => {
console.log("POST请求成功", response);
})
.catch(error => {
console.error("POST请求失败", error);
});