JavaScript Fetch API

简介

fetch() API 是用于发送 HTTP 请求的现代异步方法,它基于 Promise,比传统的 XMLHttpRequest 更加简洁、强大

示例

基本语法

fetch(url, options)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error("请求错误:", error));
  • url:请求的地址(必须)
  • options:可选的配置对象(如请求方法、头部信息、数据等)
  • fetch() 返回一个 Promise<Response> 对象

最简单的示例

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then(response => response.json()) // 解析 JSON
  .then(data => console.log("获取的数据:", data))
  .catch(error => console.error("请求错误:", error));

如何解析响应

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then(response => {
    console.log("状态码:", response.status);
    console.log("响应头:", response.headers.get("Content-Type"));
    return response.text(); // 或者 response.json(), response.blob()
  })
  .then(data => console.log("响应内容:", data))
  .catch(error => console.error("请求错误:", error));

常用解析方式:

  • response.json():解析 JSON 数据
  • response.text():解析文本数据
  • response.blob():解析二进制数据(图片、文件)
  • response.arrayBuffer():解析底层二进制数据
  • response.formData():解析表单数据

发送 POST 请求

fetch("https://jsonplaceholder.typicode.com/posts", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    title: "foo",
    body: "bar",
    userId: 1
  })
})
  .then(response => response.json())
  .then(data => console.log("返回的数据:", data))
  .catch(error => console.error("请求错误:", error));

使用 async/await 方式

async function fetchData() {
  try {
    let response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
    if (!response.ok) throw new Error(`HTTP 错误: ${response.status}`);
    let data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("请求失败:", error);
  }
}
fetchData();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值