数据请求:axios vs fetch

首先我们知道数据请求的类型有:
get , post,head, put,delete,option,…等等

数据请求在前端开发中的使用有两种形式
1.使用原生javascript提供的数据请求:
1.1 ajax( 四部曲,一般需要我们结合Promise去封装,使用不是很便利,但是效率很高 )

 //四部曲:
    //1.创建ajax对象
    var request = new XMLHttpRequest();

    //2.ajax的open方法
    request.open("get", "http://10.0.152.17/AJAX/ajaxtest", true);   
    /* 
        1.第一个参数:GET/POST请求数据--默认GET方法,
        2.open的第二个参数:接口地址
        3.open的第三个参数:是否异步     为true时,服务器请求异步进行
    */ 

    //3. ajax的send方法     就绪状态码:就绪状态--0(初始化) 1(请求建立) 2(发送完成) 3(解析) 4(完成)
    request.send( )

    //4 设置回调函数
    request.onreadystatechange = function(){
        if(request.readyState == 4 && ajax.status==200) {
        }
    }

  1. fetch( 本身结合了Promise,并且已经做好了封装,可以直接使用 )
    3. 使用别人封装好的第三方库:
    目前最流行的,使用率最高的是 axios

vue中我们最常使用的
1… vue 1.x 的版本提供了一个封装库 vue-resource , 但是到了vue 2.x版本之后,这个就弃用了
vue-resource使用方法和 axios 相似度在 95%
vue-resouce有jsonp方法,但是axios是没有的
3. vue2.x版本我们最用使用的数据请求是 axios 和 fetch

axios vs fetch
-axios需要通过script标签引入到自己的代码之中,而fetch是原生的一种方式,并且在js已经帮我们封装好了可直接使用

<script src="https://cdn.bootcss.com/axios/0.18.0/axios.js"></script>

2.axios和fetch返回的都是Promise对象,所以可以调用then和catch方法

     var p = axios.get()
            console.log( p ) // Promise

3.axios得到的结果会进行一层封装,而fetch会直接得到结果

 //axios方式获取到的数据:
{data: 3, status: 200, statusText: "OK", headers: {…}, config: {…}, …}
      config: {adapter: ƒ, transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", …}
      data: 3   //这就是获取到的数据  同下方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
 //fetch方式获取到的数据:
     3   //同上方的data中的值  直接就会得到结果

因此:axios会比fetch的安全性更高一些。

Axios总结
1.Get放法

     // A: 无参数
            axios.get(url)
                        .then(res=>console.log(res))
                        .catch(error=>conosle.log(error))
        // B: 有参数
            axios({
                url: 'http://xxx',
                method: 'get'   //默认就是get,这个可以省略,
                params: {
                    key: value
                }
            })

2.post方法、
在这里要注意: axios中post请求如果你直接使用npmjs.com官网文档, 会有坑
解决步骤:

  1. 先设置请求头
  2. 实例化 URLSearchParams的构造器函数得到params对象
  3. 使用params对象身上的append方法进行数据的传参
    代码如下 :
// 统一设置请求头||单独设置请求头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

// 实例化 URLSearchParams的构造器函数得到params对象
let params = new URLSearchParams()

// params.append(key,value) 数据的传参
params.append('a',1)
params.append('b',2)

axios({
    url: 'http://localhost/post.php',
    method: 'post',
    data: params,
    headers: {  //**单个请求设置请求头**
       'Content-Type': "application/x-www-form-urlencoded"
    }
})
    .then(res => console.log( res ))//es6中一行书写可省略花括号
    .catch( error => {
        if( error )throw error
    })

Fetch总结

1.get
fetch提供第二个参数,用来传递一些初始化的信息

//1
   fetch('https://www.baidu.com/search/error.html', {
    method: 'GET'
  	})
	  .then((res)=>{
	    return res.text()
	  })
	  .then((res)=>{
	    console.log(res)
	  })
//2
	fetch('http://localhost/get.php?a=1&b=2')
        .then(res=> res.text()) // 数据格式化 res.json() res.blob()
        .then(data => console.log( data ))
        .catch(error => {
            if( error ) throw error
        })

.注意事项:
1.fetch 的 get 请求的参数是直接连接在url上的, 我们可以使用Node.js提供的url或是qureystring模块来将:Object --> String
2.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 ))

3.post
fetch文档 --官方说明
与GET请求类似,POST请求的指定也是在fetch的第二个参数中:

fetch('https://www.baidu.com/search/error.html', {
    method: 'POST' // 指定是POST请求
  })
  .then((res)=>{
    return res.text()
  })
  .then((res)=>{
    console.log(res)
  })

POST请求参数的传递
众所周知,POST请求的参数,不能放在URL中,目的是防止信息泄露。

fetch('https://www.baidu.com/search/error.html', {
    method: 'POST',
    body: new URLSearchParams([["foo", 1],["bar", 2]]).toString() // 这里是请求对象
  })
	  .then((res)=>{
	    return res.text()
	  })
	  .then((res)=>{
	    console.log(res)
	  })

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值