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

html 复制代码
<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 基本使用

html 复制代码
//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>
相关推荐
小林ixn13 小时前
React Router 从入门到实战:一篇搞定路由配置、懒加载与嵌套路由
前端·react.js·前端框架
FeelTouch Labs13 小时前
Node.js 中的 spawn 和 exec:子进程执行的不同方式对比
node.js·编辑器·vue·vim
会飞的喵14 小时前
我给 AI Agent 做了个 UI 渲染 SDK:基于 Google A2UI 协议,让 Agent 不再只会发文字
前端框架·aigc
先吃饱再说14 小时前
从多页到单页:前端路由的演进与 React Router
前端·react.js·前端框架
shawxlee17 小时前
vue3+elementplus+sass/scss安装配置教程:使用svg图标、引入外部字体、定义变量模块、修改组件样式、一键切换主题等
vue·sass·svg·字体·element·scss·主题样式
弹简特20 小时前
【Vue3速成】07-vue3异步请求之Axios-01
vue·axios
烬羽1 天前
React Router v7 完全指南:一个 Demo 吃透前端路由
javascript·react.js·前端框架
烬羽1 天前
React Router 嵌套路由:一个 `Outlet` 引发的布局思考
react.js·面试·前端框架
烬羽1 天前
从"整个页面刷新"到"丝滑切换":手写一个 HashRouter 彻底搞懂前端路由
javascript·前端框架·全栈
弹简特2 天前
【Vue3速成】06-vue3官方库路由机制之Pinia状态管理
vue·pinia