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

  • 相关阅读:
    c#中判断对象为空的几种方式(字符串等)
    log4net示例3控制台、windows事件
    c#中如何截取Windows消息来触发自定义事件
    向ArcGIS的ToolBarControl中添加任意的windows组建的方法
    log4net示例1最简单的回滚文件记录日志程序(时间)
    Qt 定时器实现循环
    把 MPP Sample 编译成动态库
    Linux Shell 常用编程语法
    VSCode 调试
    Hisi 使用GDB调试(直接调试)
  • 原文地址:https://www.cnblogs.com/tekkaman/p/7591571.html
Copyright © 2011-2022 走看看