zoukankan      html  css  js  c++  java
  • Fetch API简单学习

    跨网络异步获取资源的功能以前是使用XMLHttpRequest对象实现的,Fetch API提供了更好的替代方案,可以很容易的被其他技术使用(如Servise Workers)

    Fetch API提供了一个全局的fetch()方法,这个方法提供了一种简单的、合乎逻辑的方式来跨网络异步获取资源。fetch()方法接收两个参数:第一个参数表示要获取的资源路径;第二个参数表示请求的配置项(可选)。该方法会返回一个Promise

    当fetch请求接收到一个代表错误的状态码时(如404、500),返回的Promise不会被标记为reject,而是被标记为resolve,但是会将response的ok属性设置为false。只有当网络错误或请求被阻止时才会被标记为reject状态

    默认情况下, fetch 不会从服务端发送或接收任何 cookies,要发送 cookies,必须设置 credentials 选项

    注意: IE浏览器不支持

    fetch请求

    请求一张图片,图片请求成功后插入到img标签中

    <img id="t">
      <script>
        var img = document.getElementById('t');
        fetch('https://cdn.86886.wang/blog/1520049901259.jpg').then(function(res){
          console.log(res)
          if(res.ok) {
            return res.blob();
          }
        }).then(function(u) {
          var url = URL.createObjectURL(u);
          img.src = url;
        })
      </script>
    

    自定义第二个参数

    GET 请求

    fetch('https://www.86886.wang/api/articles/1/3', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      },
      cache: 'default',
      mode: 'cors',
    }).then(function(res){
      if(res.ok) {
        return res.json();
      }
    }).then(function(data) {
      console.log(data)
    })
    

    POST请求

    fetch('https://www.86886.wang/api/article', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        token: 'asdf'
      },
      body: JSON.stringify({
       title: 'fetch API学习',
       content: '文章内容'
      })
    }).then(function(res){
      if(res.ok) {
        return res.json();
      }
    }).then(function(data) {
      console.log(data)
    })
    

    检测成功

    成功的状态只有一种,即response.ok属性为true。失败的情况有很多种,如404、500、网络中断

    fetch('https://cdn.86886.wang/blog/152004990125.jpg').then(function(res){
      if(res.ok) {
        return res.blob();
      }else {
        console.log('服务器响应出错了'); // 资源404、服务器500等
      }
    }).catch(function(err){
      console.log('Network response was not ok.'); // 网络出错
    })
    

    优秀文章首发于聚享小站,欢迎关注!
  • 相关阅读:
    【BUG】android.content.res.Resources$NotFoundException: File res/drawable-xxhdpi/toolbar_line.png from
    关于 折半查找 while 条件 &lt; , &lt;=
    Unity3D——加入剑痕效果(PocketRPG Trail插件)
    用外部物理路由器时使用Neutron dhcp-agent提供的metadata服务(by quqi99)
    项目经理之项目经理注意事项
    让你提前认识软件开发(37):研发流程初探
    1.RunLoop是什么?
    列表类型内置方法
    字符串类型内置方法
    数字类型内置方法
  • 原文地址:https://www.cnblogs.com/yesyes/p/15349376.html
Copyright © 2011-2022 走看看