function request(url) {
return new Promise((resolve, reject) => {
fetch(url, {
method: 'GET',
headers: {
Accept: 'application/json',
token: 'xxx',
})
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('请求失败');
}
})
.then(data => {
resolve(data);
})
.catch(error => {
reject(error);
});
});
}
// 使用示例
request('xxx')
.then(data => {
console.log('请求成功,返回数据:', data);
})
.catch(error => {
console.error('请求失败,错误信息:', error);
});
Promise请求接口并处理返回结果,使用fetch函数
于 2024-06-07 13:06:21 首次发布