fetch的使用与封装,兼与axios的区别

一、fetch

    fetch是一种XMLHttpRequest的一种替代方案,在工作当中除了用ajax获取后台数据外我们还可以使用fetch、axios来替代ajax

 

二、安装

    

执行npm install whatwg-fetch --save即可安装。

为了兼容老版本浏览器,还需要安装npm install es6-promise --save



三、fetch的基本使用

npm install whatwg-fetch --savenpm install es6-promise --saveimport 'es6-promise'import 'whatwg-fetch'
fetch(url,options).then((res)=>{ console.log(res);},function(err){ console.log(err)})

说明:

    1、fetch的返回值是一个promise对象

 

    2、options

        method:HTTP请求方式,默认是GET

 

        body:请求的参数

        fetch('/xxx', {

               method: 'post',

               body:'username=zhangsan&age=17'

       });

 

        headers:HTTP请求头

            因为一般使用JSON数据格式,所以设置ContentType为application/json

 

            credentials:默认为omit,忽略的意思,也就是不带cookie还有两个参数,same-origin,意思就是同源请求带cookie;include,表示无论跨域还是同源请求都会带cookie

 

 

    3、在.then里面第一个回调函数中处理response

 

        status(number): HTTP返回的状态码,范围在100-599之间

 

        statusText(String): 服务器返回的状态文字描述

 

        headers: HTTP请求返回头

 

        body: 返回体,这里有处理返回体的一些方法

 

        text(): 将返回体处理成字符串类型

 

       json(): 返回结果和 JSON.parse(responseText)一样

 

       blob(): 返回一个Blob,Blob对象是一个不可更改的类文件的二进制数据

如果请求一个XML格式文件,则调用response.text。如果请求图片,使用response.blob方法

 

注意:

cookie传递

必须在header参数里面加上credentials: 'include',才会如xhr一样将当前cookies带到请求中去

 

 

四、get、post请求方式

    1、get

  

1 var result = fetch('url', {        
2         credentials: 'include',        
3         headers: {            '
4             Accept': 'application/json, text/plain, */*',        
5         },     
6      });

 

    2、post

1 var result = fetch('/api/post', {        
2         method: 'POST',        
3         credentials: 'include',        
4         headers: {            
5             'Accept': 'application/json, text/plain, */*',            
6             'Content-Type': 'application/x-www-form-urlencoded'        
7         },        // 注意 post 时候参数的形式        
8         body: "a=100&b=200"    
9 });                    

 

 

五、封装get和post方法

   

 1 import 'es6-promise';
 2 import 'whatwg-fetch';
 3 import qs from 'qs';
 4 
 5 const request = {
 6   // post请求方法
 7   post(url,data = {}){
 8     return fetch(url, {
 9       method: 'POST',
10       credentials: 'include',
11       headers: {
12         'Accept': 'application/json, text/plain, */*',
13         'Content-Type': 'application/x-www-form-urlencoded'
14       },        
15       // 注意 post 时候参数的形式        
16       body: qs(data)
17     }).then(res=>{
18       return res.json()
19     }) 
20   },
21   // get请求方法
22   get(url,data = {}){
23     return fetch(url, {
24       credentials: 'include',
25       headers: {
26         'Accept': 'application/json, text/plain, */*',
27       },
28     }).then(res=>{
29       return res.json()
30     })
31   }
32 }
33 
34 export default request;

  3、使用封装

      

import request from "刚才封装请求的路径,自己填写";

// get方式测试
const handleGetRequest = () => {
  const url = "/get"  
  request.get(url)
    .then(
      res => console.log( "接口返回的数据结果就是res,其他就是对这个数据的处理",res )
    )
    .catch(
      console.log("对数据获取失败的处理")
    )
}

const handlePostRequest = () => {
  const url = "/post";
  const data = {name:"post接口请求数据"};
  request.post(url,data)
    .then(
      res => console.log( "接口返回的数据结果就是res,其他就是对这个数据的处理",res )
    )
    .catch(
      console.log("对数据获取失败的处理")
    )
}
 

五/2、不封装照样使用的方法

  例如:

 1 const handleRequest = async () => {             // async 很关键
 2 
 3   try{
 4     const response = await fetch("/get?q=参数")  //正常发起请求,并获取fetch第一个then返回的内容
 5     const data = await response.json()          //对内容进行数据类型处理
 6     console.log("接下来对接口数据进行处理",data)
 7   }catch(error){
 8     console.log("对接口请求错误进行处理",error)
 9   }
10 }

 

六、fetch与axios的区别

 

axios("http://xxx/xxx.json?a=123'").then((res)=>{     console.log(res)//这里的r是响应结果})
fetch("http://www.baidu.com").then((res)=>{        console.log(res);//是一个综合各种方法的对象,并不是请求的数据})

 

 

fetch返回的是一个未处理的方法集合,我们可以通过这些方法得到我们想要的数据类型。如果我们想要json格式,就执行response.json(),如果我们想要字符串就response.text()

 

axios 

        1、从浏览器中创建 XMLHttpRequest

        2、从 node.js 发出 http 请求

        3、支持 Promise API

        4、拦截请求和响应

        5、转换请求和响应数据

        6、自动转换JSON数据

        7、客户端支持防止CSRF/XSRF

 

fetch:

    符合关注分离,没有将输入、输出和用事件来跟踪的状态混杂在一个对象里

    更加底层,提供的API丰富(request, response)

    脱离了XHR,是ES规范里新的实现方式

 

1、fetchtch只对网络请求报错,对400,500都当做成功的请求,需要封装去处理

 

2、fetch默认不会带cookie,需要添加配置项

 

3、fetch不支持abort,不支持超时控制,使用setTimeout及Promise.reject的实

现的超时控制并不能阻止请求过程继续在后台运行,造成了量的浪费

 

4、fetch没有办法原生监测请求的进度,而XHR可以

 

posted @ 2019-08-31 22:25  HandsomeGuy  阅读(1043)  评论(0编辑  收藏  举报