Search code examples
javascriptcurlfetch

How to convert this curl command to JavaScript's fetch


I have the following cURL command:

// original curl
curl https://example.com \
  -F "id=id" \
  -F "secret=secret"

which I thought can be represented with this fetch expression:

// fetch
const body = new FormData();
body.append('id', 'id');
body.append('secret', 'secret');

return fetch('https://example.com', {
  method: 'POST',
  mode: 'no-cors',
  headers: {
    'Content-Type': 'multipart/form-data',
  },
  body,
})

And then, copying the fetch request as cURL generates the following command:

// generated curl
curl 'https://example.com' \
  -H 'content-type: multipart/form-data' \
  --data-raw $'------WebKitFormBoundaryH2Ve4S1AUbboJ21W\r\nContent-Disposition: form-data; name="id"\r\n\r\nid\r\n------WebKitFormBoundaryH2Ve4S1AUbboJ21W\r\nContent-Disposition: form-data; name="secret"\r\n\r\nsecret\r\n------WebKitFormBoundaryH2Ve4S1AUbboJ21W--\r\n' \
  --compressed

To my surprise, when using real data instead of placeholder data for the endpoint and form values, the original curl request works, but the generated curl request does not (nor does the fetch version).

Is there something obvious that I'm missing? What is the difference between the original cURL command and the fetch expression / generated cURL command?


Solution

  • I believe your goal as follows.

    • You want to convert the following curl command to fetch of Javascript.

        curl https://example.com \
          -F "id=id" \
          -F "secret=secret"
      

    In this case, how about the following script? When FormData is used, Content-Type is automatically added to the request header by including the boundary.

    Sample script:

    const body = new FormData();
    body.append('id', 'id');
    body.append('secret', 'secret');
    return fetch('https://example.com', {
      method: 'POST',
      // mode: 'no-cors' // I thought that this might not be required to be used. But please check this for your actual situation.
      body
    });
    

    Reference:

    Added:

    About your following comment,

    are you aware of a way to convert the original cURL command into something that doesn't use the -F option?

    In this case, how about manually creating the request body as follows?

    curl -H 'Content-Type: multipart/form-data; boundary=boundaryboundary' \
      -d $'--boundaryboundary\r\nContent-Disposition: form-data; name="id"\r\n\r\nid\r\n--boundaryboundary\r\nContent-Disposition: form-data; name="secret"\r\n\r\nsecret\r\n--boundaryboundary--\r\n' \
      'https://example.com'