当前位置: 首页 > news >正文

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); });

http://www.dtcms.com/a/549793.html

相关文章:

  • 机器学习-导师优选
  • 做视频网站要准备哪些资料阿里虚拟机建设网站
  • 使用局域网做网站百度手机助手网页
  • VMware-三种网络模式
  • 【weblogic】文件上传漏洞
  • 用 Rust 写一个前端项目辅助工具:JSON 格式化器
  • OrionX GPU池化社区版永久免费,算力管理焕新升级!
  • Rust 控制流深度解析:安全保证与迭代器哲学
  • 异常处理机制
  • 一元云淘网站开发android开发最全教程
  • 第 18 天:Web 服务器(Apache、Nginx、反向代理)
  • 郑州网站运营实力乐云seo如何从下载的视频查到原网站
  • nodejs有几种模块模式
  • 非法网站怎么推广海口专业的网站开发
  • 网站建设实训心得与建议安徽省工程建设信息网职称查询
  • 【高阶数据结构】AVL树
  • 三明 网站建设如何建立自己的
  • 可以做兼职的动漫网站公司网站想维护服务器
  • Go语言设计模式:桥接模式详解
  • 前端(Vue3)如何接收后端(SpringBoot)返回的文件并下载
  • 低空经济网络安全体系
  • 福建省建设资格注册中心网站东莞网站推广技巧
  • 汉阳做网站多少钱网站服务器时间查询工具
  • WPF的MVVM模式核心架构与实现细节
  • HarmonyOS 开发高级认证是什么?含金量高吗?
  • 做国外的众筹网站怎么办一个网站
  • 网站设计联盟兰州关键词优化排名
  • 【AI WorkFow】n8n 源码分析-工作流引擎实现原理(五)
  • 技术分享 | torch.profiler:利用探针收集模型执行信息的性能分析工具
  • zynq7000- linux平台 PS读写PL测试