Fetch API 的基本用法非常简单,通过调用 fetch
方法并传入请求的 URL,即可返回一个 Promise。
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
GET 请求是 Fetch API 的默认请求类型,只需传入请求 URL。
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
POST 请求需要使用配置对象,并指定请求方法和请求体。
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'John',
age: 30
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Fetch API 的配置选项非常灵活,可以设置请求方法、头信息、请求体、模式等。
fetch('https://api.example.com/data', {
method: 'PUT', // 请求方法:GET, POST, PUT, DELETE 等
headers: {
'Content-Type': 'application/json', // 请求头信息
'Authorization': 'Bearer token'
},
body: JSON.stringify({ // 请求体
name: 'Jane',
age: 25
}),
mode: 'cors', // 请求模式:cors, no-cors, same-origin
cache: 'no-cache' // 缓存模式:default, no-cache, reload, force-cache, only-if-cached
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Fetch API 返回的 Promise 解析为一个 Response 对象。可以使用 json()
、text()
等方法来解析响应体。
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
可以使用 .catch()
方法来捕获和处理请求中的错误。
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));