JavaScript的fetch函数的用法
基本语法
fetch函数用于发起网络请求,返回一个Promise对象。基本语法如下:
fetch(url, options).then(response => response.json()).then(data => console.log(data)).catch(error => console.error('Error:', error));
GET请求
发起一个简单的GET请求,获取JSON数据:
fetch('https://api.example.com/data').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('Error:', error));
POST请求
发送JSON数据到服务器:
fetch('https://api.example.com/data', {method: 'POST',headers: {'Content-Type': 'application/json',},body: JSON.stringify({key1: 'value1',key2: 'value2'})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
处理响应
fetch返回的Response对象包含多种方法处理不同格式的响应:
fetch('https://api.example.com/data').then(response => {if (response.ok) {return response.text(); // 或.json(), .blob(), .arrayBuffer()等}throw new Error('Network response was not ok');}).then(data => console.log(data)).catch(error => console.error('Error:', error));
错误处理
由于fetch只在网络错误时reject,需要手动处理HTTP错误状态:
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('Error:', error));
请求配置
可配置的选项包括method、headers、body、mode、credentials等:
fetch('https://api.example.com/data', {method: 'POST',headers: {'Content-Type': 'application/json','Authorization': 'Bearer token'},body: JSON.stringify({key: 'value'}),credentials: 'include' // 包含cookies
});
取消请求
使用AbortController可以取消fetch请求:
const controller = new AbortController();
const signal = controller.signal;fetch('https://api.example.com/data', {signal}).then(response => response.json()).then(data => console.log(data)).catch(error => {if (error.name === 'AbortError') {console.log('Fetch aborted');} else {console.error('Error:', error);}});// 取消请求
controller.abort();