当前位置: 首页 > news >正文

fetch的语法规则及常见用法

fetch() 是 JavaScript 用于发送 HTTP 请求的内置 API,功能强大,语法简洁。以下是 fetch 的语法规则及常见用法。


1. fetch 基本语法

fetch(url, options)
    .then(response => response.json()) // 解析 JSON 响应体
    .then(data => console.log(data))   // 处理数据
    .catch(error => console.error("Error:", error)); // 处理错误
  • url:请求的地址(必填)。
  • options:可选的请求配置对象(如 methodheadersbody 等)。

2. fetch 请求方法

(1)GET 请求

GET 请求用于获取数据,通常不需要 body

fetch("https://api.example.com/data")
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error("Error:", error));

或带参数:

const params = new URLSearchParams({ id: 123, name: "Tom" });
fetch(`https://api.example.com/data?${params}`)
    .then(response => response.json())
    .then(data => console.log(data));

(2)POST 请求

POST 用于发送数据,通常需要 bodyheaders

fetch("https://api.example.com/data", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ id: 123, name: "Tom" })
})
.then(response => response.json())
.then(data => console.log(data));

(3)PUT / PATCH 请求(更新数据)

  • PUT:完整更新资源
  • PATCH:部分更新资源
fetch("https://api.example.com/user/123", {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ name: "Updated Name" })
})
.then(response => response.json())
.then(data => console.log(data));

(4)DELETE 请求

DELETE 请求用于删除数据,通常不需要 body

fetch("https://api.example.com/user/123", {
    method: "DELETE"
})
.then(response => response.json())
.then(data => console.log(data));

3. fetch 选项(options)详解

fetch(url, {
    method: "POST", // 请求方法
    headers: { "Content-Type": "application/json" }, // 请求头
    body: JSON.stringify({ key: "value" }), // 请求体
    mode: "cors", // 跨域请求模式
    credentials: "include", // 携带 Cookie
    cache: "no-cache", // 缓存模式
    redirect: "follow" // 自动跟随重定向
})

常用 options 配置

配置项说明
method请求方法(GET、POST、PUT、DELETE、PATCH等)
headers请求头,例如 Content-TypeAuthorization
body发送的请求数据,通常为 JSON 或 FormData
modecors(跨域),same-origin(同源)
credentialsinclude(携带 Cookie),omit(不带 Cookie)
cacheno-cache(不缓存),reload(强制刷新)
redirectfollow(自动重定向),error(遇到重定向报错)

4. 处理响应(Response 对象)

fetch 返回的是一个 Promise,解析后得到 Response 对象:

fetch("https://api.example.com/data")
    .then(response => {
        console.log(response.status);  // HTTP 状态码
        console.log(response.headers); // 响应头
        return response.json();        // 解析 JSON
    })
    .then(data => console.log(data));

Response 方法

方法作用
response.text()解析为文本格式
response.json()解析为 JSON
response.blob()解析为 Blob(二进制数据,如图片)
response.arrayBuffer()解析为 ArrayBuffer
response.formData()解析为 FormData

5. 处理错误

fetch 只有在网络错误时才会进入 catch,如果服务器返回 4xx 或 5xx 需要手动抛出异常:

fetch("https://api.example.com/data")
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => console.log(data))
    .catch(error => console.error("Fetch error:", error));

6. async/await 方式

fetch 也可以和 async/await 搭配使用,使代码更清晰:

async function fetchData() {
    try {
        const response = await fetch("https://api.example.com/data");
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        const data = await response.json();
        console.log(data);
    } catch (error) {
        console.error("Fetch error:", error);
    }
}

fetchData();

7. 进阶用法

(1)携带 Cookie(跨域请求)

如果请求涉及跨域并需要携带 Cookie,必须设置 credentials

fetch("https://api.example.com/data", {
    method: "GET",
    credentials: "include" // 允许携带 Cookie
});

(2)上传文件

使用 FormData 进行文件上传:

const formData = new FormData();
formData.append("file", fileInput.files[0]);

fetch("https://api.example.com/upload", {
    method: "POST",
    body: formData
})
.then(response => response.json())
.then(data => console.log(data));

(3)超时处理

fetch 本身不支持超时,需要用 Promise.race() 处理:

function fetchWithTimeout(url, timeout = 5000) {
    return Promise.race([
        fetch(url),
        new Promise((_, reject) =>
            setTimeout(() => reject(new Error("Request Timeout")), timeout)
        )
    ]);
}

fetchWithTimeout("https://api.example.com/data")
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error(error));

8. 总结

用法代码示例
基本 GETfetch(url).then(res => res.json()).then(console.log);
POST 发送 JSONfetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) })
处理错误fetch(url).then(res => { if (!res.ok) throw new Error(res.status); return res.json(); })
携带 Cookiefetch(url, { credentials: "include" })
上传文件fetch(url, { method: "POST", body: formData })
超时处理Promise.race([fetch(url), new Promise((_, r) => setTimeout(() => r(new Error("Timeout")), 5000))])
http://www.dtcms.com/a/99811.html

相关文章:

  • EasyExcel 与 Apache POI:Java 操作 Excel 的详解
  • 6-1-1 利用AI完成一个可视化看板
  • 如何监控和优化服务器的 CPU 性能
  • 视频联网平台智慧运维系统:智能时代的城市视觉中枢
  • 记录一次Dell服务器更换内存条报错解决过程No memory found
  • 基于微波光子信道的图像传输系统matlab仿真,调制方式采用OFDM+QPSK,LDPC编译码以及LS信道估计
  • 机器学习——集成学习框架(GBDT、XGBoost、LightGBM、CatBoost)、调参方法
  • 计算机基础
  • 睡眠健康领域的智能硬件设备未来的发展趋势
  • C语言术语
  • 算法刷题记录——LeetCode篇(1.3) [第21~30题](持续更新)
  • 分库分表详解
  • 关于c++的FLOYD算法 P2910 [USACO08OPEN] Clear And Present Danger S 题解
  • Spring Boot 整合 RabbitMQ:注解声明队列与交换机详解
  • 高级SQL技巧
  • Linux(8.6)rsync
  • 33. Java 流程控制语句 If-Then-Else 语句
  • [原创](现代C++ Builder 12指南): 如何使用System.JSON?
  • Gitee批量删除仓库
  • 美食菜谱数据集 | 智能体知识库 | AI大模型
  • 力扣HOT100之普通数组:41. 缺失的第一个正数
  • Cannot find a valid baseurl for repo: centos-sclo-sclo/x86_64
  • Vue实现的表格多选方案支持跨页选择和回显功能
  • DNS网络攻击:原理剖析、危害解读与全面防御指南
  • 【Python LeetCode 专题】每日一题
  • 【20期获取股票数据API接口】如何用Python、Java等五种主流语言实例演示获取股票行情api接口之沪深A股实时最新分时MACD数据及接口API说明文档
  • 本地缓存之Guava Cache
  • Linux CentOS 7 搭建我的世界服务器详细教程 (丐版 使用虚拟机搭建)
  • CTFshow命令执行(55-71)
  • 24_原型和原型链_this