fetch-axios简述和简单用法

网络请求

fetch

官方文档

在项目开发过程中,我们向服务端发送请求,一般会使用三种方式, XMLHttpRequest(XHR)FetchjQuery实现的AJAX,第三方包axios。其中, XMLHttpRequest(XHR)Fetch是浏览器的原生API,jquery的ajax其实是封装了XHR(这种使用起来就比较复杂了,不推荐使用),而fetch和axios都是封装了promise来处理异步。

fetch api是浏览器内置的api,和axios不同。

基于promise的封装,形成的异步数据请求的标准,兼容性不好

chrome浏览器 103.0.5060.134(正式版本) (64 位) 控制台输入fetch.

Snipaste_2022-08-01_22-06-21

兼容性

Snipaste_2022-08-01_22-20-36

fetch使用

​
fetch('url', {
    method: 'get'
    //options
}).then(function(response) {
    //返回请求的数据
}).catch(function(err) {
    // 出错了;使用catch进行捕获
​
});
​
使用fetch发送get请求
​
        fetch("/json/text.json").then(res => res.json()).then(res => {
          console.log(res);
        }).catch(err => console.log(err))

注意:

第一个then里的res返回的是状态码和响应头,第二个里面返回的是数据,使用catch捕获异常。

get请求也可以传参:url?username=zx&password=xxxx

使用fetch发送post请求
发送application/x-www-form-urlencoded
        fetch("/user.json", {
          method: "post",
          headers: {
            "Content-type": "application/x-www-form-urlencoded"
          },
          body: "username=zx&password=123456"
        }).then(res => res.json).then(res => {
          console.log(res);
        }).catch(err => {
          console.log(err);
        })

真如你所见,我在发起请求时,options并不是必须的,所以在上个例子使用fetch发送get请求里,我并没有给配置options。一般来说options是用来设置调用时的Request对象,使用方法可以参考上面的例子。

  • method - 支持 GET, POST, PUT, DELETE, HEAD
  • url - 请求的 URL
  • headers - 对应的 Headers 对象
  • body - 请求参数(JSON.stringify 过的字符串或’name=jim\u0026age=22’ 格式)
发送application/json
        fetch("", {
          method: "post",
          headers: {
            "Content-type": "application/json"
          },
          body: JSON.stringify({ "name": "zs", "password": "123456" })
        }).then(res => res.json).then(res => {
          console.log(res);
        }).catch(err => console.log(err))

注意:

因为fetch默认是get请求,所以这里要标清楚请求方式。

同时也要包含,post.body里的内容,比如请求头,请求体等。

axios

官方文档

优点:异步无刷新进行局部数据的更新,用户体验好 缺点:需要三方包引入

使用axios发送get请求

        axios.get("/day3/json/mi1.json").then(res => {
​
          this.list = res.data.data.sections
          // console.log(this.list);
        }).catch(err => {
          console.log(err);
        })
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

抗争的小青年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值