美文网首页
Fetch的使用

Fetch的使用

作者: agamgn | 来源:发表于2020-01-30 08:03 被阅读0次

    前言

     前端发展迅速,前端请求自然也发展迅速,从原生的XHR到jquery ajax,再到现在的axios和fetch。这节主要是记录Fecth的使用。

    一、什么是Fetch

     Fetch本质上是一种标准,该标准定义了请求、响应和绑定的流程。Fetch是一种HTTP数据请求的方式,是XMLHttpRequest的一种替代方案。Fetch不是ajax的进一步封装,而是原生js。Fetch函数就是原生js,没有使用XMLHttpRequest对象。

    二、前置知识

    参考Feach API部分解释

    三、使用Fetch

    2.1、fetch() 方法的使用

     Fetch API 提供了一种全局fetch()方法,该方法位于 WorkerOrGlobalScope 这一个 mixin 中 方法用于发起获取资源的请求。它返回一个 promise,这个 promise 会在请求响应后被 resolve,并传回 Response 对象。原文

    2.1、参数

    主要有两个参数

    • input 参数可以是字符串,包含要获取资源的 URL。也可以是一个 Request 对象。
    • options 是一个可选参数。一个配置项对象,包括所有对请求的设置。可选的参数有:

    method: 请求使用的方法,如 GET、POST。
    headers: 请求的头信息,包含与请求关联的Headers对象。
    body: 请求的 body 信息。注意 GET 或 HEAD 方法的请求不能包含 body 信息
    mode: 请求的模式,如 cors、 no-cors 或者 same-origin。
    credentials: 请求的 credentials,如 omit、same-origin 或者 include。为了在当前域名内自动发送 cookie , 必须提供这个选项。

    fetch('api/data.json', {
      method:'POST', //请求类型GET、POST
      headers:{},// 请求的头信息,形式为 Headers 对象或 ByteString。
      body:{},//请求发送的数据 blob、BufferSource、FormData、URLSearchParams(get或head方法中不能包含body)
      mode:'',//请求的模式,是否跨域等,如 cors、 no-cors 或者 same-origin。
      credentials:'',//cookie的跨域策略,如 omit、same-origin 或者 include。
      cache:'', //请求的 cache 模式: default, no-store, reload, no-cache, force-cache, or only-if-cached.
    }).then(function(response) { ... });
    

    案例:

    fetch("//api.github.com/users",{methods:"GET"})
    .then(res=>res.json())
    .then(json=>console.log(json))
    

    四、fetch的一些例子

    4.1、处理text/html响应

    fetch(url).then(response=>response.text())
        .then(data=>console.log(data))
        .catch(e=>console.log('error' + e));
    

    4.2、获取头信息:

    fetch(url).then((response)=>{
        console.log(response.status);
        console.log(response.statusText);
        console.log(response.headers.get('Content-Type'));
        console.log(response.headers.get('Date'));
        return response.json();
    }).then(data=>console.log(data))
      .catch(e=>console.log('error' + e);
    

    4.3、设置头信息

    fetch(url,{
        headers:{
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        }
    }).then(response=>response.json())
      .then(data=>console.log(data))
      .catch(e=>console.log('error' + e);
    

    4.4、提交表单

    fetch(url,{
        method: 'post',
        body: new FormData(document.getElementById('form'))
    }).then(response=>response.json())
      .then(data=>console.log(data))
      .catch(e=>console.log('error' + e);
    

    4.5、提交json数据

        fetch(url,{
                method: 'post',
                body: JSON.stringify({
                    username: document.getElementById('username').value,
                    password: document.getElementById('password').value
                })
            }).then(response=>response.json())
              .then(data=>console.log(data))
              .catch(e=>console.log('error' + e)
    

    fetch常见坑

    1、Fetch 请求默认是不带 cookie 的
    需要设置 fetch(url, {credentials: 'include'})
    2、fetch请求对某些错误http状态不会reject
    3、不可以取消

    1.fetch不支持abort,不支持超时控制,使用setTimeout及Promise.reject的实现的超时控制并不能阻止请求过程继续在后台运行,造成了流量的浪费。
    2.fetch没有办法原生监测请求的进度,而XHR可以
    4.fetch不支持超时timeout处理
    5.fetch不支持JSONP

    总结

    fetch在主流的浏览器最新版中,都是兼容的
    代码地址

    相关文章

      网友评论

          本文标题:Fetch的使用

          本文链接:https://www.haomeiwen.com/subject/njsrzctx.html