You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ES6中实现函数参数可选:合并GET与POST请求函数

合并GET/POST的通用Fetch函数优化方案

可以把两个函数合并成一个通用函数,通过可选参数实现body的按需添加,同时保留原有配置的兼容性:

async function fetchData(url = "", method = "GET", data) {
  // 基础配置保留原有设定
  const fetchOptions = {
    method,
    mode: "cors",
    credentials: "include",
    headers: {
      "Content-Type": "application/json",
    },
  };

  // 仅当请求为POST(或其他需要body的方法)且传入了data时,添加body字段
  if ((method === "POST" || method === "PUT" || method === "PATCH") && data) {
    fetchOptions.body = JSON.stringify(data);
  }

  const response = await fetch(url, fetchOptions);
  // 可根据需求添加响应处理,比如解析JSON
  // return response.json();
}

关键优化点说明:

  • 可选参数设计:method默认设为GET,data不设默认值(仅在需要时传入),适配不同请求场景
  • 按需添加body:通过判断请求方法和data是否存在,避免GET请求中出现多余的body字段(虽然fetch会忽略GET的body,但这样更规范)
  • 扩展性:默认支持POST/PUT/PATCH这类需要body的请求,若只需支持GET和POST,可把判断条件简化为method === "POST" && data

使用示例:

// 发起GET请求
fetchData("https://your-api-url.com/list");

// 发起POST请求,传入数据
fetchData("https://your-api-url.com/create", "POST", { key: "value" });

内容的提问来源于stack exchange,提问作者user2399035

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 22:10:14