风华正茂、时光流逝、真爱时光、努力创建辉煌。

【react】 react 中 前后端数据的交互方式 (原生的ajax、jq的ajax、axios、fetch )

 

 

 

这是fetch  请求数据的方式

 

 

 

 


 

 

---fetch---基本使用

 

一、fetch

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

 二、安装

  

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

 

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

 

 

三、fetch的基本使用 

  

复制代码
npm install whatwg-fetch --save
npm install es6-promise --save
import '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

复制代码
var result = fetch('url', {
        credentials: 'include',
        headers: {
            'Accept': 'application/json, text/plain, */*',
        },    
 });
复制代码

  2、post

复制代码
var result = fetch('/api/post', {
        method: 'POST',
        credentials: 'include',
        headers: {
            'Accept': 'application/json, text/plain, */*',
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        // 注意 post 时候参数的形式
        body: "a=100&b=200"
    });
复制代码

 

五、封装get和post方法

  1、get

 

复制代码
import 'es6-promise'
import 'whatwg-fetch'

export default (url)=>({
    var result = fetch(url, {
        credentials: 'include',
        headers: {
            'Accept': 'application/json, text/plain, */*',
        },    
   })
   .then(res=>res.json());
   
   return result
})
复制代码

 

  2、post

复制代码
import 'es6-promise'
import 'whatwg-fetch'
import qs from 'qs';
export default (url,data)=>({
    var result = fetch(url, {
        method: 'POST',
        credentials: 'include',
        headers: {
            'Accept': 'application/json, text/plain, */*',
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        // 注意 post 时候参数的形式
        body: qs(data)
    })
    .then(res=>res.json())
    
    return result;
})
复制代码

 

 

 六、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-09-23 16:57  野马,程序源改造新Bug  阅读(5204)  评论(0编辑  收藏  举报