异步 HTTP 请求
fetch
是一个用于进行异步 HTTP 请求的 JavaScript API。
fetch
基本用法
// 使用 fetch 进行 GET 请求
fetch('https://api.example.com/data')
.then(response => {
// 检查响应是否成功
if (!response.ok) {
throw new Error('Network response was not ok');
}
// 解析响应数据为 JSON
return response.json();
})
.then(data => {
// 处理 JSON 数据
console.log(data);
})
.catch(error => {
// 处理错误
console.error('There has been a problem with your fetch operation:', error);
});
发送 POST 请求
// 使用 fetch 进行 POST 请求
fetch('https://api.example.com/data', {
method: 'POST', // 指定请求方法为 POST
headers: {
'Content-Type': 'application/json' // 设置请求头
},
body: JSON.stringify({
key1: 'value1',
key2: 'value2'
}) // 将数据转换为 JSON 字符串
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
处理不同的响应格式
fetch('https://api.example.com/data')
.then(response => {
// 处理文本响应
return response.text();
})
.then(text => {
console.log(text);
});
fetch('https://api.example.com/image')
.then(response => {
// 处理 Blob 响应
return response.blob();
})
.then(blob => {
const img = document.createElement('img');
img.src = URL.createObjectURL(blob);
document.body.appendChild(img);
});
使用 Async/Await
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('There has been a problem with your fetch operation:', error);
}
}
fetchData();
错误处理
处理错误时,fetch
只会在网络故障或请求被阻止的情况下拒绝 Promise
。对于 HTTP 错误状态码(如 404 或 500),需要手动检查响应的 ok
属性:
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('HTTP error! status: ' + response.status);
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
fetch
并行的异步请求
// 定义要获取的 URL 列表
const urls = [
'https://api.example.com/data1',
'https://api.example.com/data2',
'https://api.example.com/data3'
];
// 使用 fetch 并行请求所有 URL
Promise.all(urls.map(url => fetch(url)))
.then(responses => {
// 检查所有响应是否都成功
responses.forEach(response => {
if (!response.ok) {
throw new Error(`Network response was not ok for ${response.url}`);
}
});
// 将所有响应解析为 JSON
return Promise.all(responses.map(response => response.json()));
})
.then(dataArray => {
// 处理所有解析后的数据
console.log(dataArray);
})
.catch(error => {
// 处理任何请求中的错误
console.error('There has been a problem with your fetch operation:', error);
});
Async/Await 进行并行请求
async function fetchDataInParallel(urls) {
try {
// 并行请求所有 URL
const responses = await Promise.all(urls.map(url => fetch(url)));
// 检查所有响应是否都成功
responses.forEach(response => {
if (!response.ok) {
throw new Error(`Network response was not ok for ${response.url}`);
}
});
// 将所有响应解析为 JSON
const dataArray = await Promise.all(responses.map(response => response.json()));
// 处理所有解析后的数据
console.log(dataArray);
} catch (error) {
// 处理任何请求中的错误
console.error('There has been a problem with your fetch operation:', error);
}
}
// 定义要获取的 URL 列表
const urls = [
'https://api.example.com/data1',
'https://api.example.com/data2',
'https://api.example.com/data3'
];
// 调用 fetchDataInParallel 函数
fetchDataInParallel(urls);
更多内容
使用 Fetch - Web API | MDN
https://www.ruanyifeng.com/blog/2020/12/fetch-tutorial.html