@darrion.kuhn
To convert a curl
command to a JavaScript fetch
request, you need to replicate the same HTTP method, headers, request body, and URL. Here's an example of how to convert a curl
command to a fetch
request in JavaScript:
Curl command:
1
|
curl -X POST -H "Content-Type: application/json" -d '{"name":"John", "age":30}' https://example.com/api |
Equivalent JavaScript fetch
request:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fetch('https://example.com/api', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'John', age: 30 }) }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error)); |
In the JavaScript fetch
request:
After making the fetch
request, you can handle the response using .then()
and .catch()
methods. In the example, the response is parsed as JSON using the response.json()
method, and the resulting data is logged to the console.