欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > fetch怎么使用

fetch怎么使用

2025/4/2 15:11:18 来源:https://blog.csdn.net/xuelian3015/article/details/142419372  浏览:    关键词:fetch怎么使用

fetch 是一个现代、强大的、基于 Promise 的网络请求 API,用于在浏览器中发起网络请求(如异步获取资源)。它提供了一种更加简洁和灵活的方式来替代 XMLHttpRequest。下面是 fetch 的基本使用方法和一些示例。

基本语法

fetch(url, options).then(response => {// 处理响应if (!response.ok) {throw new Error('Network response was not ok');}return response.json(); // 或者 response.text(), response.blob() 等,取决于你需要的数据类型}).then(data => {// 处理响应数据console.log(data);}).catch(error => {// 处理错误console.error('There was a problem with your fetch operation:', error);});

参数

  • url:要请求的资源的 URL。
  • options(可选):一个配置项对象,用于自定义请求,比如设置请求方法(GET、POST 等)、请求头(Headers)、请求体(Body)等。

示例

GET 请求
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('Fetch error:', error);});
POST 请求
const url = 'https://api.example.com/items';
const data = { name: 'New Item', description: 'This is a new item.' };fetch(url, {method: 'POST', // 或者 'PUT'headers: {'Content-Type': 'application/json',},body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => console.log(data))
.catch((error) => console.error('Error:', error));

注意事项

  • fetch 不会自动处理 JSON 转换,因此如果你期望获取 JSON 格式的数据,你需要在 .then() 中调用 response.json()
  • fetch 只会拒绝(reject)网络错误,而不会对 HTTP 错误状态码(如 404 或 500)进行拒绝。因此,你需要检查 response.ok(等同于 response.status >= 200 && response.status < 300)来确保请求成功。
  • fetch 遵循 CORS(跨源资源共享)策略,因此如果你从前端应用向不同源的服务器发送请求,需要确保服务器支持 CORS。
  • 默认情况下,fetch 不会发送或接收任何 cookies,也不会添加任何认证信息到请求中。如果你需要发送 cookies,需要将 credentials 选项设置为 'include'
fetch(url, {credentials: 'include',
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词