JS fetch()

发布: (2026年5月6日 GMT+8 13:06)
2 分钟阅读
原文: Dev.to

Source: Dev.to

什么是 fetch()

  • fetch() 是一个内置函数,用于发起网络/HTTP 请求。
  • 它返回一个 Promise
  • 该 Promise 在成功时解析为一个 Response 对象,代表服务器的响应。
  • 然后你可以检查请求状态,并以多种格式(如文本或 JSON)提取响应体。

HTTP 方法

  • GET – 获取数据
  • POST – 创建数据
  • PUT – 更新数据
  • DELETE – 删除数据

语法

fetch(url, options)
  • url → API 端点
  • options → 方法、请求头、请求体等

调用 fetch(url) 会发送请求并返回一个 Promise。

fetch(url)
  .then(response => {
    // response 包含状态 (200, 404 …)、headers、body(尚未可读)
  });

读取响应体

response.json()   // 将 body 转换为 JavaScript 对象(返回 Promise)
response.text()   // 将 body 作为纯文本返回(返回 Promise)

基本的 GET 请求

// 获取 JSON 数据
fetch("https://jsonplaceholder.typicode.com/posts")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(err => console.log(err));

// 获取纯文本
fetch("https://jsonplaceholder.typicode.com/posts")
  .then(response => response.text())
  .then(data => console.log(data))
  .catch(err => console.log(err));

错误处理

fetch("https://jsonplaceholder.typicode.com/post")
  .then(res => {
    if (!res.ok) {
      throw new Error("HTTP Error: " + res.status);
    }
    return res.json();
  })
  .then(data => console.log(data))
  .catch(err => console.log(err));
0 浏览
Back to Blog

相关文章

阅读更多 »