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.'); // 网络出错
})

posted @ 2021-09-28 18:47  wmui  阅读(83)  评论(0编辑  收藏  举报