zoukankan      html  css  js  c++  java
  • fetch的相关概念以及二次封装(与axios二次封装道理类似)

    1、fetch:

    ①fetch是window下面的一个方法;

    ②脱离了XHR,是ES的规范;

    ③兼容性不太好

    ④基于promise的API

    2、安装:cnpm install whatwg-fetch -S

    3、GET请求:(默认)

    fetch(url+?key=val,{   

      headers:请求头

      method:请求方式

    })

    4、POST:

    fetch(url,{

      headers:请求头

      method:请求方式

      body:post传递参数的属性

    })

    5、特点:

      不管是get还是post请求,当请求成功之后,第一个.then中是一个未处理的结果集;

    第二个.then中才是最后的结果(也就是我们想要得到的结果);fetch默认是不会携带cookie的,

    如果想要携带cookie,需要设置credentials:"include"

    6、

     fetch(url)
        .then((res)=>{结果集的处理})
        .then((data)=>{
            console.log(data);
        })
    
        结果集的处理:你想要的数据格式是哪种格式 text  json  blob  formData

    7、fetch的二次封装,可配合async,await使用

    import {fetch as fetchPro} from "whatwg-fetch";
    import qs from "qs";
    
    
    
    const get = (url,data)=>{
        let str = "";
    
        for(var key in data){
            str += "&"+key+"="+data[key];
        }
    
        url = url+str.substr(1);
    
    
       return fetchPro(url,{
    method:"GET", headers:{
    "content-type":"application/json" }, credentials:"include" }) .then(res=>res.json()) } const post = (url,data)=>{ return fetchPro(url,{ method:"POST", headers:{ "content-type":"application/x-www-form-urlencoded" }, credentials:"include", body:qs.stringify(data) }) .then(res=>res.json()) } export default { get, post }
  • 相关阅读:
    C#,asp.net,命名空间名,类名,方法名的获得
    asp.net引用用户控件
    SQL数据是否存在(是否有数据)判断,表,存储过程是否存在
    asp:Button 事件,点击事件 html Button runat="sever"
    CSS图片最大大小限制
    asp.net 路径
    Js实现网站的重定向,Js转向网址,Js跳转
    ViewState 页面状态保留
    vs 附加到进程
    sql XML处理,sp_xml_preparedocument,openxml
  • 原文地址:https://www.cnblogs.com/cqdd/p/10385003.html
Copyright © 2011-2022 走看看