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 }
  • 相关阅读:
    4.运算符&if条件控制
    欢迎进入软件构建的世界
    Linux是什么
    计算机概论
    Java基础11集合(2)
    基础06-存储过程和函数,流程控制结构,变量
    基础05-常见约束,tcl事物控制语言,视图,标识列
    基础04-联合查询,dml语言,ddl语言
    基础03-子查询,分页查询
    基础00-随笔里的数据来源(库,表数据)
  • 原文地址:https://www.cnblogs.com/cqdd/p/10385003.html
Copyright © 2011-2022 走看看