• axios与fetch实现数据请求


    axios与fetch实现数据请求

    框架级的数据请求

    1.axios(第三方库 --- 别人封装好的库)

    2.fetch(js原生提供)

    3.vue这边数据请求的发展

    ​ -- vue-resource(Vue 以前自己封装使用的请求类库),但是 vue-resource作者已经放弃更新了,不推荐再使用,但用法与axios和fetch相似。 vue-resource有jsonp数据请求类型

    4.axios 和 fetch 没有jsonp数据请求类型

    ​ --axios 和 fetch都是primose形式

    1.axios 的 GET 请求

    1.导入方式 cdn导入 https://www.bootcdn.cn/

    <script src="https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.min.js"></script>
    

    2.当cdn导入axios时,会全局暴露一个axios对象

    console.log(axios)  
    
    //控制台输出: 
    ƒ (){for(var n=new Array(arguments.length),r=0;r<n.length;r++)n[r]=arguments[r];return e.apply(t,n)} 
    
    

    3.axios请求不跨域的数据时:

    	<div id=app>
            <!-- 访问模拟数据 -->
            <button @click='getDate'>get - mock - json(自己虚拟json)</button>
        </div>
        <script>
            new Vue({
                el: '#app',
                methods: {
                    getDate() {
                        //进行get请求
                        //axios.get() //axios.post()
                        //axios(options)  //options 可以查看npm中axios文档
                        var p = axios({
                            url: 'data/data.json' //模拟数据地址
                        })
                        .then(res => console.log(res)) //axios会对请求的结果进行封装(提高安全性)
                        .catch(error => console.log(error))
                        
                        console.log(p); // Promise {<pending>} 对象
    
                    }
                }
            })
        </script>
    	
    	
    

    4.axios请求跨域数据时候 :

    ​ 4.1. 设置headers:{} 如果不设置请求头会有跨域的报错ACAO

    ​ 4.2 发送数据的形式是params:{}

    ​ 4.3 并不是所有网站都可以

     get_be_data() {
                        //跨域请求数据 卖座电影
                        axios({
                                url: 'https://m.maizuo.com/gateway',
                                headers: {
                                    'X-Client-Info':                             '{"a":"3000","ch":"1002","v":"5.0.4","e":"15610891489006546420515"}',
                                    'X-Host': 'mall.film-ticket.film.list'
                                },
                                methods: 'get',
                                params: {
                                    cityId: 110100,
                                    pageNum: 1,
                                    pageSize: 10,
                                    type: 1,
                                    k: 3298060
                                },
                            })
                            .then(res => console.log(res)) 
                            .catch(error => console.log(error))
                    },
    

    5.axios请求自己后端的接口:

    ​ 5.1由于同源策略的限制,会出现跨域问题

    ​ 后端解决跨域: 设置请求头 header('Access-Control-Allow-Origin:*');

    ​ 前端解决:利用反向代理 ;

    后端接口: (路径:http://localhost/get.php)

    <?php
    
    //header('Access-Control-Allow-Origin:*'); //这个没加就会有跨域问题
    
    $a = $GET['a'];
    
    $b = $_GET['b'];
    
    echo $a + $b
    

    axios发送请求:

     get_myself_php_data () {
            axios({
              url: 'http://localhost/get.php',
              params: {
                a: 1,
                b: 2
              }
            })
              .then( res => console.log( res ))
              .catch( error => console.log( error ))
          },
                        
    

    以上都是axios的GET请求


    2.axios 的 post 请求

    1.post请求官网上有些坑 如下代码依然存在跨域问题

              axios({
                    url: 'http://localhost/post.php',
                    method: 'post',
                    data: {
                      a: 2,
                      b: 2
                    }
                  })
                    .then( res => console.log( res ))
                    .catch( error => console.log( error ))
                  
    

    解决方案:

    1.先设置请求头

    2.实例化URLSeachParams的构造器函数得到params对象

    3.使用params对象身上的append方法进行数据的传参

    注意:post的传参方式params.append(key,value)

    // 统一设置请求头
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; 
    let params = new URLSearchParams()
    
    // params.append(key,value)
    
    params.append('a',1)
    params.append('b',2)   //post请求独特的传参方式
    
    axios({
        url: 'http://localhost/post.php',
        method: 'post',
        data: params,
          headers: {  //单个请求设置请求头  统一设置请求头以后可以不用设置
           'Content-Type': "application/x-www-form-urlencoded"
        }
    })
    .then(res => {console.log( res )})
    .catch( error => {if( error ){throw error}})
    

    fetch

    1.fetch的get请求

    1.fetch是原生js提供的,所以它可以做全局变量使用,它是挂载在windows对象身上的

    2.特点: fetch要手动进行一次数据格式化 (axios内部已经格式化),也是promise对象(axios也是)

     fetch('./data/data.json')
              .then( res => res.json() ) //对数据进行格式化
              .then( data => console.log( data ) ) // 这里的data就是格式化后的数据
              .catch( error => console.log( error ))
    
    

    3.fetch发送get请求是 参数直接写在url上了 所以不用发送数据

    4.fetch格式化有三种处理方式

    ​ 4.1 .json() 格式化 json 类型数据,将json类型string(字符串)转化成 json对象

    ​ 4.2 .text() 格式化文本

    ​ 4.3 .blob() 格式化二进制数据

    2.fetch的post请求

    参考MDN上的fetch文档(比较权威)

    https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch

    fetch( 'http://localhost/post.php',{
              method: 'post',
              headers: new Headers({
                'Content-Type': 'application/x-www-form-urlencoded' // 指定提交方式为表单提交
              }),
              body: new URLSearchParams([["a", 1],["b", 2]]).toString() 
            })
              .then( res => res.text() )
              .then( data => console.log( data ))
              .catch( error => console.log( error ))
    
    

    fetch 如果按照官网文档书写post请求,也有坑,携带的数据出现了问题

    传参:body: new URLSearchParams([["a", 1],["b", 2]]).toString()

    请求头设置:

    headers: new Headers({

    ​ 'Content-Type': 'application/x-www-form-urlencoded' // 指定提交方式为表单提交

    ​ }),

  • 相关阅读:
    站立会议04(第二阶段)附加站立会议02、03
    第二阶段冲刺---站立会议01
    网络:Session原理及存储
    网络:Xen理解
    网络:LVS负载均衡原理
    网络:OSPF理解
    语音笔记:信号分析
    语音笔记:CTC
    语音笔记:矢量量化
    语音笔记:MFCC
  • 原文地址:https://www.cnblogs.com/xiaohanga/p/11067087.html
Copyright © 2020-2023  润新知