解决跨域问题之fetch的使用

 

 

 

一、介绍

    fetch 提供了一个获取资源的接口 (包括跨域)。

    fetch 的核心主要包括:Request , Response , Header , Body

    利用了请求的异步特性 --- 它是基于 promise 的

1.作用:fetch这个API, 是专门用来发起Ajax请求的;

fetch('/url').then(data=>{
    return data.text();
}).then(ret=>{
    //注意,这里才是得到的最终数据
    console.log(ret);
});

 


2.fetch是由原生JS提供的API,专门用来取代XHR这个对象的;

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

3.发起Get 请求

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

4.发起Post请求 例如: 

var sendDate = new URLSearchParams()
 sendDate.append("name",'ls')
 sendDate.append("age", 30)

 fetch("url", {
   method: "post",
   body: sendDate,  //要发给服务器的数据
  mode:'cors'
}) .then(response => response.json()) .then(data => console.log(data))
fetch(URL, {
            method: 'post',
            body:JSON.stringify(obj),
            headers:{
                'Content-Type': 'application/json'
            }
        })
        .then(function (response) {
            return response.text();
        })
        .then(function (myJson) {
            alert(myJson);
        });

 

posted @ 2022-09-15 09:36  喆星高照  阅读(2894)  评论(0编辑  收藏  举报