anxios和fetch数据请求

anxios

  • 使用别人封装好的第三方库:目前最流行的,使用率最高的是 axios
  • axios得到的结果会进行一层封装,而fetch会直接得到结果

axios

    {data: 3, status: 200, statusText: "OK", headers: {}, config: {},}
    config: {adapter: ƒ, transformRequest: {}, transformResponse: {}, timeout: 0, xsrfCookieName: "XSRF-TOKEN",}
    data: 3
    headers: {content-type: "text/html; charset=UTF-8"}
    request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload,}
    status: 200
    statusText: "OK"
    __proto__: Object

anxios get方式

注意:anxios返回的是promise对象

案例如下:

//这里引用了bootstrap
//html文件如下:

<div id="app">
    <div class="container">
      <div class="row">
        <button 
          type="button" 
          class="btn btn-primary" 
          @click = "get"
        > axios-get </button>
      </div>
    </div>
  </div>

格式如下:axios.get(url).then(res=>console.log(res).catch(error=>conosle.log(error))

new Vue({
   el:'#app',
   methods:{
------------方法1-----------------
       get(){
        var p = axios.get('localhost/php/get.php?a=1&&b=1');//参数直接放在url后面
        p
        .then( res => console.log(res))
        .catch( e => {
            if(e) throw e
        })
       }
----------方法2--------------
       get(){
           anxios({
               url:'localhost/php/get.php',
               method:'get',//默认是get请求,可以省略
               params:{ //params中跟着的是get请求的参数
                   a:1,
                   b:1  
               }
           })
           .then( res => console.log(res))
           .catch( e => {
            if(e) throw e
        })
      }
   }
})

anxios post方式

注意:anxios返回的是promise对象

  • 解决步骤:
    • 1.先设置请求头
    • 2.实例化 URLSearchParams的构造器函数得到params对象
    • 3.使用params对象身上的append方法进行数据的传参
      案例如下:
//这里引用了bootstrap
//html文件如下:

<div id="app">
    <div class="container">
      <div class="row">
        <button 
          type="button" 
          class="btn btn-primary" 
          @click = "post"
        > axios-post </button>
      </div>
    </div>
  </div>
new Vue({
    el:'#app',
    methods:{
        post(){
            let params = new URLSearchParams();
            params.append('a',5);//传参
            params.append('b',5);
            anxios({
                url:'localhost/php/post.php',
                method:'post',
                data:params,
                headers:{
                     'Content-Type': "application/x-www-form-urlencoded"
                }
            })
            .then( res => {console.log(res)})
            .catch( e => {
                if(e) throw e
            })
        }
    }
})

fetch数据请求

注意fetch返回的是一个promise对象

  • A: fetch 的 get 请求的参数是直接连接在url上的,我们可以使用Node.js提供的url或是qureystring模块中的querystring.stringify方法来实现Object --> String
  • B: fetch 的请求返回的是Promise对象,所以我们可以使用.then().catch(),但是要记住.then()至少要写两个,第一个then是用来格式化数据的,第二个then是可以拿到格式化后的数据格式化处理方式有
fetch('./data.json')
.then(res=>{
   res.json() //res.text() res.blob()//数据格式化
})
.then( data => console.log(data))
.catch( error => console.log( error ))
  • 案例如下:
//html文件如下:
<div id="app">
    <div class="container">
      <div class="row">
        <button type="button" class="btn btn-primary" @click = "get"> fetch-get </button>
        <button type="button" class="btn btn-primary" @click = "post"> fetch-post </button>
        <button type="button" class="btn btn-primary" @click = "json"> fetch-get-json数据 </button>
      </div>
   </div>
</div>
  • fethch get方式请求数据
new Vue({
    el:'#app',
    methods:{
        get(){
            fetch('http://localhost/get.php?a=1&b=2')
            .then( res => res.text())//对数据进行格式化 res.json() res.blob()
            .then( data => console.log(data)
            .catch( e => {
                if(e) throw e;
            })
        }
    }
})
  • fethch post方式请求数据
new Vue({
    el:'#app',
    methods:{
        post(){
            var fetch_post = fetch('http://localhost/post.php',{
                method:'post',
                headers: new Headers({//解决跨域
                   'Content-Type': "application/x-www-form-urlencoded" 
                }),
                body: new URLSearchParams([ // 进行参数的修改
                    ['a',1],
                    ['b',1]
                ]).toString()
            })
            .then( res => res.text())
            .then( data => console.log(data))
            .catch(e =>{
               if(e) throw e
            })
        }
    }
})
  • fethch 请求json数据
new Vue({
    el:'#app',
    methods:{
        json(){
           fetch('./data/data.json')
           .then( res => res.json())
           .then( data => console.log(data))
           .catch(errpr => {
              if(error) throw error
           })
        }
    }
})
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值