跳到内容
🛠️ToolsShed

Fetch 转 cURL 工具

将 JavaScript fetch() 调用转换为等效的 cURL 命令。

关于此工具

Fetch to cURL 转换器将 JavaScript 的 fetch() 调用转换为等效的 cURL 命令行语句。该工具弥补了现代网络开发和命令行调试之间的差距,使测试 API、重现网络问题和在不同环境间共享请求变得更加简单。无论您是调试失败的 API 调用还是为团队文档记录 HTTP 请求,这些格式之间的转换都能节省时间并减少手动转录错误。

要使用转换器,请将 JavaScript fetch() 代码粘贴到输入区域中,然后点击转换按钮。该工具立即将 fetch 语法(包括标题、请求正文、身份验证令牌和 HTTP 方法)转换为等效的 cURL 格式。然后您可以复制生成的 cURL 命令并在终端、Postman 或其他 HTTP 测试工具中直接执行。这使得在不同平台和调试上下文中验证 API 请求是否运行相同变得简单。

转换器处理常见的 fetch 模式,包括 JSON 有效负载、表单数据、自定义标题和各种 HTTP 方法(GET、POST、PUT、DELETE、PATCH)。该工具对在前端代码和命令行实用程序之间频繁移动的开发人员、DevOps 工程师和 API 维护人员非常有价值。通过消除手动转换步骤,您可以专注于解决实际问题,而不是重新编写请求语法。

常见问题

代码实现

import requests
import subprocess

# Python requests equivalent of fetch()
# fetch("https://api.example.com/users", { method: "GET" })
response = requests.get("https://api.example.com/users",
    headers={"Authorization": "Bearer mytoken"})

# Convert to equivalent cURL command string
def requests_to_curl(method, url, headers=None, data=None):
    parts = ["curl", "-X", method.upper()]
    if headers:
        for k, v in headers.items():
            parts += ["-H", f"'{k}: {v}'"]
    if data:
        import json
        parts += ["-d", f"'{json.dumps(data)}'"]
    parts.append(f"'{url}'")
    return " ".join(parts)

# Example
curl_cmd = requests_to_curl(
    "POST",
    "https://api.example.com/users",
    headers={
        "Content-Type": "application/json",
        "Authorization": "Bearer abc123",
    },
    data={"name": "Alice", "email": "alice@example.com"},
)
print(curl_cmd)

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.