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

  • 相关阅读:
    B/S架构大文件上传问题
    大文件上传解决方案-支持断点续传的文件上传插件(转)
    前端大文件分片上传
    B/S大文件分片上传
    Web大文件分片上传
    .NET大文件分片上传
    ASP.NET大文件分片上传
    leetCode(37):Implement Queue using Stacks
    poj 3928 Ping pong(树状数组)
    从零開始学Swift之Hello World进化版
  • 原文地址:https://www.cnblogs.com/tekkaman/p/7591571.html
Copyright © 2011-2022 走看看