初探 XHR 中的 Fetch 请求

发布于 2022-10-18 21:37:35 字数 3092 浏览 214 评论 0

fetch

与 XMLHttpRequest(XHR)类似,fetch() 方法允许你发出 AJAX 请求。区别在于 Fetch API 使用 Promise,因此是一种简洁明了的 API,比 XMLHttpRequest 更加简单易用。

比较 XMLHttpRequest(传统 Ajax)

创建步骤:

  • 创建 XMLHttpRequest 对象,也就是创建一个异步调用对象
  • 创建一个新的 HTTP 请求,并指定该 HTTP 请求的方法、URL 及验证信息
  • 发送 HTTP 请求
  • 处理响应,获取异步调用返回的数据

可以发现,主要的不同点在于:传统 Ajax 使用事件处理器,而不是 Promise 对象,并且请求的发起完全依赖于xhr对象所提供的方法。

fetch 语法

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

使用 ES6 的 箭头函数:

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

使用 async/await 来做最终优化:

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

使用 await 后,写异步代码就像写同步代码一样爽。await 后面可以跟 Promise 对象,表示等待 Promise resolve() 才会继续向下执行,如果 Promise 被 reject() 或抛出异常则会被外面的 try…catch 捕获。

GET 请求

fetch(url, {
    method: "GET", //默认
    headers:{
      "Accept": "application/json, text/plain, */*"
    }
})
.then(response => response.json())
.then(data => console.log(data))
.catch(e => console.log("Oops, error", e))

POST 请求

fetch(url, {
    method: "POST",
    headers: {
      "Accept": "application/json, text/plain, */*",
        "Content-type":"application:/x-www-form-urlencoded; charset=UTF-8"
    },
    body: "name=hzzly&age=22"
})
.then(response => response.json())
.then(data => console.log(data))
.catch(e => console.log("Oops, error", e))

使用 Fetch 请求发送凭证

要使用 Fetch 发送带有诸如 cookie 之类的凭证的请求。你可以在选项对象中将 credentials 属性值设置为 include:

fetch(url,{
  credentials: "include"
})

封装 POST 请求

//将对象拼接成 name=hzzly&age=22 的字符串形式
function params(obj) {
  let result = ''
  for(let item in obj) {
    result += `&${item}=${obj[item]}`
  }
  if(result) {
    result = result.slice(1)
  }
  return result
}
function post(url, paramsObj) {
  let result = fetch(url, {
    methods: 'POST',
    credentials: "include"
    headers: {
        "Accept": "application/json, text/plain, */*",
          "Content-type":"application:/x-www-form-urlencoded; charset=UTF-8"
      },
      body: params(paramsObj)
  })
  return result
}
let obj = {
  name: 'hzzly',
  age: 22
}
post(url, obj)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(e => console.log("Oops, error", e))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

始终不够

暂无简介

文章
评论
27 人气
更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文