【十月学习随笔】关于Fetch

MDN Fetch文档

 

fetch()是 XMLHttpRequest 的升级版,用于在 JavaScript 脚本里面发出 HTTP 请求。该方法提供了一种简单,合理的方式来跨网络异步获取资源。

 

  • 比较fetch()和 XMLHttpRequest 

XMLHttpRequest

var xhr=new XMLHttpRequest()
   xhr.open('get','/some/url',true)
   xhr.responseType = 'json';
   xhr.send()
   xhr.onreadystatechange=function(){
       if(xhr.status=200&&xhr.readyState==4){
           console.log(xhr.response)
       }
   }

fetch

fetch('https://api.github.com/users/ruanyf')
  .then(response => response.json())
  .then(json => console.log(json))
  .catch(err => console.log('Request Failed', err)); 

 

fetch方式使用Promise,相比较XMLHttpRequest更加的简洁。

  • 基本的fetch请求格式

// url (必须), options (可选)
fetch('/some/url', {
    method: 'get'
}).then(function(response) {

}).catch(function(err) {
    // 出错了;等价于 then 的第二个参数,但这样更好用更直观 :(

});
/*
method - 支持 GET, POST, PUT, DELETE, HEAD
url - 请求的 URL
headers - 对应的 Headers 对象
body - 请求参数(JSON.stringify 过的字符串或’name=jim\u0026age=22’ 格式)
*/
  • Response响应

fetch()请求成功以后,会接收一个Response实例,fetch后的第一个then用于处理数据的形式

fetch('https://api.github.com/users/ruanyf')
  .then(response => response.json())
  .then(json => console.log(json))
  .catch(err => console.log('Request Failed', err)); 
  • 使用fetch发送跨域 cookies

fetch(url,{
credentials:"include"
})
//默认的 credentials 为 same-origin

 

posted @ 2021-10-24 12:07  Oranges  阅读(130)  评论(0编辑  收藏  举报