zoukankan      html  css  js  c++  java
  • Using Fetch

    Using Fetch

      This kind of functionality was previously achieved using XMLHttpRequest. Fetch provides a better alternative that can be easily used.

      需要注意以下2点:

      1)The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.

      2)By default, fetch won't send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the credentials init option must be set).

    var myImage = document.querySelector('img');
    
    fetch('flowers.jpg').then(function(response) {
      return response.blob();
    }).then(function(myBlob) {
      var objectURL = URL.createObjectURL(myBlob);
      myImage.src = objectURL;
    });

      下面的示例,控制了HTTP Header

    var myHeaders = new Headers();
    
    var myInit = { method: 'GET',
                   headers: myHeaders,
                   mode: 'cors',
                   cache: 'default' };
    
    fetch('flowers.jpg', myInit).then(function(response) {
      return response.blob();
    }).then(function(myBlob) {
      var objectURL = URL.createObjectURL(myBlob);
      myImage.src = objectURL;
    });

    credentials

    fetch('https://example.com', {
      credentials: 'include'  
    })
    // The calling script is on the origin 'https://example.com'
    
    fetch('https://example.com', {
      credentials: 'same-origin'  
    })
    fetch('https://example.com', {
      credentials: 'omit'  
    })

    错误处理

    fetch('flowers.jpg').then(function(response) {
      if(response.ok) {
        return response.blob();
      }
      throw new Error('Network response was not ok.');
    }).then(function(myBlob) { 
      var objectURL = URL.createObjectURL(myBlob); 
      myImage.src = objectURL; 
    }).catch(function(error) {
      console.log('There has been a problem with your fetch operation: ' + error.message);
    });

    Request对象

      Request() accepts exactly the same parameters as the fetch() method. You can even pass in an existing request object to create a copy of it:

    var myHeaders = new Headers();
    
    var myInit = { method: 'GET',
                   headers: myHeaders,
                   mode: 'cors',
                   cache: 'default' };
    
    var myRequest = new Request('flowers.jpg', myInit);
    
    fetch(myRequest).then(function(response) {
      return response.blob();
    }).then(function(myBlob) {
      var objectURL = URL.createObjectURL(myBlob);
      myImage.src = objectURL;
    });

    Headers

      All of the Headers methods throw a TypeError if a header name is used that is not a valid HTTP Header name. 

      A good use case for headers is checking whether the content type is correct before you process it further. 

    fetch(myRequest).then(function(response) {
        var contentType = response.headers.get("content-type");
        if(contentType && contentType.includes("application/json")) {
          return response.json();
        }
        throw new TypeError("Oops, we haven't got JSON!");
      })
      .then(function(json) { /* process your JSON further */ })
      .catch(function(error) { console.log(error); });

    Response

    • Response.status — An integer (default value 200) containing the response status code.
    • Response.statusText — A string (default value "OK"),which corresponds to the HTTP status code message.
    • Response.ok — seen in use above, this is a shorthand for checking that status is in the range 200-299 inclusive. This returns a Boolean.

      

    参考:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

  • 相关阅读:
    SQL Server创建复合索引时,复合索引列顺序对查询的性能影响
    SQL 查询性能优化----解决书签查找
    从源码分析 Spring 基于注解的事务
    jQuery最佳实践(不断更新中...)
    Java 8 LongAdders:管理并发计数器的正确方式
    Java中的显示锁 ReentrantLock 和 ReentrantReadWriteLock
    在IE8等不支持placeholder属性的浏览器中模拟placeholder效果
    颠覆式前端UI开发框架:React
    Whitecoin区块链钱包高级功能使用命令
    消息队列使用的四种场景介绍
  • 原文地址:https://www.cnblogs.com/tekkaman/p/7591571.html
Copyright © 2011-2022 走看看