Convert curl to JavaScript Fetch API
Convert curl commands to JavaScript fetch() API calls. Handle headers, JSON bodies, authentication, and async/await patterns for browser and Node.js.
Detailed Explanation
Converting curl to JavaScript Fetch
The Fetch API is the modern standard for making HTTP requests in JavaScript, available in all browsers and Node.js 18+. Converting curl to fetch is essential for frontend and full-stack developers.
GET Request
curl:
curl https://api.example.com/users
JavaScript:
const response = await fetch("https://api.example.com/users");
const data = await response.json();
POST with JSON
curl:
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-d '{"name": "Alice"}'
JavaScript:
const response = await fetch("https://api.example.com/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Alice" }),
});
const data = await response.json();
Bearer Token Authentication
curl:
curl -H "Authorization: Bearer token123" https://api.example.com/me
JavaScript:
const response = await fetch("https://api.example.com/me", {
headers: { "Authorization": "Bearer token123" },
});
Error Handling
Unlike curl, fetch does not reject on HTTP error status codes. You must check response.ok manually:
const response = await fetch("https://api.example.com/data");
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
Key Differences from curl
| curl behavior | fetch equivalent |
|---|---|
| Auto-follows redirects | redirect: "follow" (default) |
-X METHOD |
method: "METHOD" |
-H "Key: Value" |
headers: { "Key": "Value" } |
-d 'body' |
body: "string" |
-u user:pass |
headers: { "Authorization": "Basic " + btoa("user:pass") } |
| Cookie handling | credentials: "include" |
| Timeout | AbortSignal.timeout(ms) |
Abort and Timeout
const response = await fetch("https://api.example.com/data", {
signal: AbortSignal.timeout(5000),
});
Fetch provides a clean, promise-based API that integrates naturally with modern async/await JavaScript patterns.
Use Case
A frontend developer needs to convert a curl command from API documentation into a fetch call for a React or Vue.js application making client-side API requests.