fetch

225 阅读1分钟

1️⃣ fetch 是什么?

fetch 是浏览器自带的一个方法,用来发 HTTP 请求
它的最大特点是:异步(不会卡死页面)+ 基于 Promise(可以配合 await 很方便)。

2️⃣ 最简单的用法

假设我们有一个接口:

https://api.example.com/data

我们想获取它的数据,最基础的写法:

fetch("https://api.example.com/data")
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(err => console.error("出错了", err));

3️⃣ 配合 async/await

await 会更直观:

async function getData() {
  try {
    const res = await fetch("https://api.example.com/data");
    const data = await res.json();
    console.log(data);
  } catch (err) {
    console.error("出错了", err);
  }
}

📌 两次 await 的意义:

  1. 第一次 await 等的是“请求完成,拿到 HTTP 响应”(Response 对象)。
  2. 第二次 await 等的是“把响应体解析成 JSON”。

4️⃣ fetch 的几个重要点

(1)fetch 默认是 GET 请求

fetch("/api/user")

这就相当于:

fetch("/api/user", { method: "GET" })

(2)发送 POST 请求

fetch("/api/user", {
  method: "POST",
  headers: {
    "Content-Type": "application/json" // 告诉服务器我发的是 JSON
  },
  body: JSON.stringify({ name: "张三", age: 18 }) // 请求体
})

(3)检查请求是否成功

fetch 不会因为 404 / 500 直接报错,它只会在网络错误时(比如断网)才进 catch
所以要自己判断:

const res = await fetch(url);
if (!res.ok) {
  throw new Error(`请求失败:${res.status}`);
}

res.ok 会在状态码 200~299 时返回 true

蓝桥杯真题

题目:www.lanqiao.cn/problems/18…

export const useMessageStore = defineStore("message", () => {
  const messageState = ref([]);
  const MockUrl = "./data.json";
  let getUserMessage = async () => {
    // TODO:待补充代码
    try {
      const res = await fetch(MockUrl);
      if (!res.ok) {
        throw new Error(`请求失败:${res.status}`);
      }
      const { data } = await res.json();
      messageState.value = data;
      console.log("数据加载成功:", data);
    } catch (err) {
      console.error("获取数据出错:", err);
    }
    // TODO:END
  };

  return {
    messageState,
    getUserMessage,
  };
});