[ES6] fetch

可能遇到的问题:

  • Fetch 请求默认是不带 cookie 的,需要设置 fetch(url, {credentials: 'include'})

 

  • 服务器返回 400,500 错误码时并不会 reject,只有网络错误这些导致请求不能完成时,fetch 才会被 reject。

 

  • 原生fetch没有abort方法,如果用polyfill需要自己封装一个出去,或者安装一个封装完整的包(例如axios)

 

  • fetch的默认请求method是get,若是要特别指定其他类型需要在第二个参数里指定。

 


使用 XHR 发送一个 json 请求

var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';

xhr.onload = function() {
  console.log(xhr.response);
};

xhr.onerror = function() {
  console.log("Oops, error");
};

xhr.send();

 



使用 Fetch

fetch(url).then(function(response) {
  return response.json();
}).then(function(data) {
  console.log(data);
}).catch(function(e) {
  console.log("Oops, error");
});

 


Fetch + arrow function

fetch(url).then(response => response.json())
  .then(data => console.log(data))
  .catch(e => console.log("Oops, error", e))

 



async/await

async function f(url){
      try {
      let response = await fetch(url);
      let data = await response.json();
      console.log(data);
    } catch(e) {
      console.log("Oops, error", e);
    }
} 

 

 

更多例子

fetch('/hello').then((response) => {
  return response.text();
}).then((data) => {
  console.log(data);
}).catch((e) => {
  console.log("Oops, error");
});

fetch('/', { method: 'POST' }).then((response) => {
  return response.text();
}).then((data) => {
  console.log(data);
}).catch((e) => {
  console.log("Oops, error");
});

fetch('/user', { method: 'PUT' }).then((response) => {
  return response.text();
}).then((data) => {
  console.log(data);
}).catch((e) => {
  console.log("Oops, error");
});

fetch('/user', { method: 'DELETE' }).then((response) => {
  return response.text();
}).then((data) => {
  console.log(data);
}).catch((e) => {
  console.log("Oops, error");
});

 

var myImage = document.querySelector('img');

var myHeaders = new Headers();
myHeaders.append('Content-Type', 'image/jpeg');

var myInit = { method: 'GET',
               headers: myHeaders,
               mode: 'cors',
               cache: 'default' };

var myRequest = new Request('flowers.jpg');

fetch(myRequest,myInit).then(function(response) {
  ...
});

//var myRequest = new Request('flowers.jpg',myInit);
    
//fetch(myRequest).then(function(response) {
//  ...
//});    

 

更多

转载于:https://www.cnblogs.com/qingmingsang/articles/5650153.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值