fetch the use of (cross-domain problem to be solved)

1. Role: fetch this API, Ajax is designed to initiate the request;
2.fetch protozoan JS API is provided, designed to replace the XHR object;

  fetch("请求的url地址")
  .then(response => res.json() )
  .then(data => console.log(data))
  //注意: 第一个.then 中获取到的不是最终数据,而是一个中间的数据流对象;
  // 注意: 第一个  .then 中获取到的数据, 是一个 Response 类型对象;
  // 注意: 第二个 .then 中,获取到的才是真正的 数据;
  1. Get request initiated

     // 默认  fetch("url") 的话, 发起的是 Get 请求
     fetch("url")
     .then(response => {
         //这个 response  就是 服务器返回的可读数据流, 内部存储的是二进制数据
         // .json() 的作用,就是 读取 response 这个二进制数据流,并把 读取到的数
         //  据,转为 JSON 格式的Promise 对象
         return response.json()
      })
      .then(data => {
               //这离  第二个 .then 中拿到的 data, 就是最终的数据
         console.log(data)
      })
    
  2. Initiate Post request;

     例如: 
     var sendDate = new URLSearchParams()
     sendDate.append("name",'ls')
     sendDate.append("age", 30)
    
     fetch("url", {
       method: "post",
       body: sendDate  //要发给服务器的数据
     })
     .then(response => response.json())
     .then(data => console.log(data))
    

Reproduced in: https: //www.jianshu.com/p/d0931efde495

Guess you like

Origin blog.csdn.net/weixin_34161083/article/details/91202365