解决跨域问题之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 @   喆星高照  阅读(3461)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2021-09-15 TypeScript 中装饰器的理解?应用场景?
点击右上角即可分享
微信分享提示