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

vue3(四)-基础入门之 fetch 与 axios

一、fetch

1、axios和fetch的区别

Axios 和 Fetch 都是 JavaScript 中用于发送 HTTP 请求的 API,它们的主要区别在以下方面:

1.Axios 支持更广泛的浏览器和 Node.js 版本,而 Fetch 只能在较新的浏览器中使用,或需要使用 polyfill 兼容旧版浏览器。
2.Axios 可以拦截请求和响应,可以全局配置默认的请求头、超时时间等,而 Fetch 目前不支持这些功能。
3.Axios 默认返回 JSON 格式的数据,而 Fetch 返回的是 Response 对象,需要自己通过 Response 的方法(如 json()、text() 等)将结果转换成所需的格式。
4.Axios 对于请求错误可以直接抛出异常,方便进行错误处理,而 Fetch 的错误处理比较繁琐,需要手动检查 Response.ok 属性。
5.fetch是原生js自带的,axios是封装的原生的xhr

以上文字参考链接

2.fetch 基本使用

  • 第一个 then 返回一个 respond 对象,第二个 then 可以获取返回数据

  • fetch 请求默认是不带 cookie 的,需要设置 fetch(url,(credentails:''include))

<script>//  get请求fetch('./lib/test.json').then(res => res.json()).then(datas => console.log(datas.students))// post 请求fetch('./users', {method: 'post',headers: { 'Content-Type': 'application/x-www-form-urlencoded' },body: 'age = 22'}).then(res => res.json()).then(datas => console.log(datas))
</script>

3.axios 基本使用

//cdn 导入
<script src="https://unpkg.com/axios@1.1.2/dist/axios.min.js"></script><!-- <script src="https://cdn.jsdelivr.net/npm/axios@1.1.2/dist/axios.min.js"></script> -->
<script>// axios get请求axios.get('./lib/test.json').then(res => {console.log(res.data.students)})// 1.axios post请求axios.post('./users', {age: 22,name: 'zs'}).then(res => {console.log(res.data)}).catch(error => console.error(error))// 2.axios post请求axios({method: 'post',url: './sers',headers: {Accept: 'application/json','Content-Type': 'application/x-www-form-urlencoded'},timeout: 2000, // 超时时间data: {age: '19',name: 'zs'}}).then(res => {console.log(res.data)}).catch(error => console.error('请求超时'))</script>
http://www.lryc.cn/news/246213.html

相关文章:

  • 2016年五一杯数学建模C题二孩政策问题解题全过程文档及程序
  • 学习c#的第二十四天
  • ELK企业级日志分析平台——logstash
  • laravel8中常用路由使用(笔记四)
  • 理解 <script> 标签的 defer 和 async 属性
  • sql中group by和having的使用
  • 用python自行开发的流星监控系统meteor_monitor(第二篇)
  • Slf4j使用Logback时,Logback如何初始化
  • css之svg 制作圆及旋转
  • 学习.NET验证模块FluentValidation的基本用法(续1:其它常见用法)
  • lv11 嵌入式开发 UART实验 11
  • Ubuntu22.04下打包发布Qt5.15应用程序的方法
  • 初级JVM
  • MySQL数据库 编程入门
  • 6.golang函数
  • 软件可靠性测试常见的方法
  • C/C++字节对齐
  • 【Android知识笔记】性能优化专题(四)
  • DC电源模块的散热措施
  • uniapp H5、小程序、APP端自定义不同运行环境(开发、测试、生产)、自定义条件编译平台、以及动态修改manifest.json值讲解
  • centos 显卡驱动安装(chatglm2大模型安装步骤一)
  • 05_属性描述符
  • vue day2
  • 四川劳动保障杂志社四川劳动保障编辑部四川劳动保障杂志2023年第10期目录
  • python数据类型
  • 大数据-之LibrA数据库系统告警处理(ALM-37004 Datanode主备不同步或者断连)
  • 带你用uniapp从零开发一个仿小米商场_2.创建空白项目及公共样式引入
  • 1144. 连接格点,Kruskal算法,二维矩阵压缩为一维
  • C++ : 友元(未完结)
  • Nginx 服务器 SSL 证书安装部署