Fetch API 返回值获取方法

注意事项
- Fetch API 默认不会发送或接收任何 cookies,需要设置
credentials: 'include' - Fetch 只有在网络错误时才会 reject,HTTP 错误状态(如 404、500)不会导致 Promise reject
- 每个 Body 方法(如 .text(), .json())只能使用一次,如果需要多次使用,需要先调用 .clone() 方法
- 使用 .json() 时,如果响应不是有效的 JSON,会抛出错误
常用写法
使用 async/await 语法
async function fetchData() {try { const response = await fetch('https://jsonplaceholder.typicode.com/users/1'); if (!response.ok) { throw new Error('网络响应不正常'); } const data = await response.json(); console.log(data); // 处理数据 } catch (error) { console.error('请求失败:', error); }
}使用 .text() 方法获取文本数据
fetch('https://jsonplaceholder.typicode.com/posts/1').then(response => { if (!response.ok) { throw new Error('网络响应不正常');} return response.text(); }).then(text => { console.log(text); // 这是文本数据 }) .catch(error => { console.error('请求失败:', error); });使用 .json() 方法获取 JSON 数据
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => { if (!response.ok) { throw new Error('网络响应不正常'); } return response.json();}) .then(data => { console.log(data); // 这是 JSON 数据
}) .catch(error => { console.error('请求失败:', error);
});使用 .blob() 方法获取二进制数据
fetch('https://picsum.photos/200/100')
.then(response => { if (!response.ok) { throw new Error('网络响应不正常'); } return response.blob();
}) .then(blob => { // 创建对象 URLconst imageUrl = URL.createObjectURL(blob); // 使用图片数据 const img = document.createElement('img'); img.src = imageUrl; document.body.appendChild(img); }) .catch(error => { console.error('请求失败:', error); });使用 .formData() 方法获取表单数据
fetch('https://httpbin.org/post', {method: 'POST', body: new URLSearchParams({ 'name': '张三', 'email': 'zhangsan@example.com' }) }).then(response => response.formData()) .then(formData => { // 处理表单数据 for (let pair of formData.entries()) { console.log(pair[0] + ': ' + pair[1]); }}) .catch(error => { console.error('请求失败:', error); });