function httpRequest(url, data = null, method = 'GET') {
return new Promise((resolve, reject) => {
let options = {
method: method,
headers: {
'Content-Type': 'application/json'
}
};
if (data) {
options.body = JSON.stringify(data);
}
fetch(url, options)
.then(response => {
if (!response.ok) {
reject(new Error(`请求失败,状态码: ${response.status}`));
} else if (response.status === 204) {
resolve(null);
} else {
return response.json();
}
})
.then(data => {
resolve(data);
})
.catch(error => {
reject(error);
});
});
}
原生js http请求
zhuc
2025-01-22
20 阅读