Converting curl to fetch

Viewed 7831

I can successfully curl an endpoint and get a 200 response, but when I use the curl to fetch converter, the api complains about on of the body params. I don't have any control over the api so I'm not really sure what's going on there.

Here is my successful curl:

curl -v -X POST https://someurl -d 'param1=someValue' -d 'param2=somOtherValue'

Using https://kigiri.github.io/fetch/, suggests using following body in the fetch request:

"param1=someValue&param2=someOtherValue"

But using that gives me the response:

Param1 is not valid

Any idea on what the fetch body should look like to make it work just like the curl?

EDIT:

Converting the fetch back to a curl helps to understand the difference. So, this works:

curl -v -X POST https://someurl -d 'param1=someValue' -d 'param2=someOtherValue'

But this doesn't:

curl -v -X POST https://someurl -d 'param1=someValue&param2=someOtherValue'

This seems to be the case for this specific api, still I can't change the api so I would like to find the equivalent fetch body for the first curl

3 Answers

you can use this to convert curl to fetch:

fetch("https://someurl", {
  body: "param1=someValue&m2=somOtherValue",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded"
  },
  method: "POST"
})

Working snippet

fetch("https://my-json-server.typicode.com/typicode/demo/posts", {
  body: "param1=someValue&m2=somOtherValue",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded"
  },
  method: "POST"
}).then(res => console.log(res));

I use postman client to convert api request between languages.

  1. Import -> Raw text (paste your curl command here)

enter image description here

  1. Code -> select your language

enter image description here

Although the accepted answer is very good already,

but perhaps you could also use this nice helper to directly convert

https://kigiri.github.io/fetch/

It works well in translating the headers and similar stuff

Related