Home > Mobile >  curl succeed but Javascript fetch failed
curl succeed but Javascript fetch failed

Time:10-25

I have my JS fetch code this:

var myHeaders = new Headers();
myHeaders.append("accept", "application/json");
myHeaders.append("Authorization", "Bearer asdfasdfasdfasdfasdf");
myHeaders.append("Content-Type", "multipart/form-data");

var formdata = new FormData();
formdata.append("images", fileInput.files[0], "_265_.pdf");
formdata.append("cards", fileInput.files[0], "_180_.pdf");
formdata.append("organization", "org");

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: formdata,
  redirect: 'follow'
};

fetch("https://site/route?match_cut=0.64&Img_cut=0.45&card_cut=0.45&Img_card_cut=0.45&card_img_cut=0.45", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

Everytime I make this request to my server which is Fastapi, the response I got were always {detail: 'There was an error parsing the body'} Though, I can successfully call to my server with below curl command:

curl -X 'POST' \
  'https://site/route?match_cut=0.64&Img_cut=0.45&card_cut=0.45&Img_card_cut=0.45&card_img_cut=0.45' \
  -H 'accept: application/json' \
  -H 'Authorization: Bearer asdfasdfasdfasdfasdf' \
  -H 'Content-Type: multipart/form-data' \
  -F 'images=@_265_.pdf;type=application/pdf' \
  -F 'reference=' \
  -F 'cards=@_180_.pdf;type=application/pdf' \
  -F 'organization=org'

Is there something missing in my fetch request ?

CodePudding user response:

The line myHeaders.append("Content-Type", "multipart/form-data"); caused my server failed to parse the request, removing it make everything back to normal.

  • Related