How each curl option maps to fetch
| curl | fetch |
|---|---|
-X POST | method: "POST". With -d, curl uses POST even without -X. |
-H "Name: value" | An entry in headers. |
-d / --data-raw with JSON | body: JSON.stringify({...}) |
--json '{...}' | The body, plus Content-Type and Accept set to application/json. |
-u user:pass | Authorization: Basic ... with the Base64 of user:pass. |
-F field=value | A FormData body. Don't set Content-Type yourself; fetch adds the boundary. |
Check the status code
Unlike curl with --fail, fetch() only rejects on network errors. A 400 or 500 response still resolves, so check response.ok before reading the body, as the generated code does.
Keep the token out of the browser
$TOKEN in the command is a shell variable. In the generated code it's a plain string, so replace it with a value from your environment, such as process.env.API_TOKEN on a server. Don't ship secret API keys in browser code, where anyone can read them.
Frequently asked questions
Why does my request work in curl but fail with CORS in the browser?
Browsers enforce CORS and curl doesn't. The API has to allow your site's origin, or you send the request from your own server and call that from the browser.
Why do I get 415 Unsupported Media Type?
The server didn't receive a JSON content type. Keep "Content-Type": "application/json" in the headers when the body is JSON.stringify(...).
Can I use this code in Node.js?
Yes. Node.js 18 and newer have fetch built in, so the code runs as it is, inside an async function or an ES module with top-level await.