Fetch API 是一种新的客户端 API,它允许在 JavaScript 中访问和操作网络请求。它主要用于浏览器,可以用于发出网络请求,以获取或更新服务器上的资源。Fetch API 提供了一个更加简单的接口,使得发起网络请求变得更加容易。
Fetch API 的使用方法
Fetch API 的使用方法非常简单,只需要调用 window.fetch() 方法即可,该方法接收两个参数:要请求的 URL 和一个可选的配置对象。
fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
一旦我们发起了网络请求,fetch() 方法会返回一个 Promise 对象,我们可以使用 then() 方法来指定成功和失败的回调函数。
fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
// Do something with the data
})
.catch(err => {
// Do something with the error
});
Fetch API 的实例
下面是一个使用 Fetch API 发起一个 GET 请求的实例:
fetch('https://example.com/api/getData')
.then(response => response.json())
.then(data => {
// Do something with the data
})
.catch(err => {
// Do something with the error
});
下面是一个使用 Fetch API 发起一个 POST 请求的实例:
fetch('https://example.com/api/postData', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'John Doe',
age: 30
})
})
.then(response => response.json())
.then(data => {
// Do something with the data
})
.catch(err => {
// Do something with the error
});
Fetch API 还支持其他类型的请求,比如 PUT、DELETE 等,只需要把 method 属性设置为相应的请求类型即可。
- Fetch API 是一种新的客户端 API,它允许在 JavaScript 中访问和操作网络请求。
- Fetch API 的使用方法非常简单,只需要调用 window.fetch() 方法即可。
- Fetch API 提供了一个更加简单的接口,使得发起网络请求变得更加容易。
- Fetch API 还支持其他类型的请求,比如 PUT、DELETE 等,只需要把 method 属性设置为相应的请求类型即可。