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

  • 相关阅读:
    第二周学习进度总结
    《大道至简》阅读收获及个人总结
    代码层面解释安全性
    2020年大三下学期第二周学习心得
    信息化领域热词分类分析及解释实战
    2020年新型冠状病毒疫情分析实战
    《架构漫谈》个人理解概括
    北京市信件内容爬虫实例——首都之窗
    2020寒假生活学习日记(十五)
    2020寒假生活学习日记(十四)
  • 原文地址:https://www.cnblogs.com/tekkaman/p/7591571.html
Copyright © 2011-2022 走看看