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

2024-06-04 1151阅读

一、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"))

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

    3.axios 基本使用

    //cdn 导入
    
        
    
          // 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: './users',
            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('请求超时'))
    
    

    免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们,邮箱:ciyunidc@ciyunshuju.com。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

    目录[+]