2

I was having an API where I am calling a get request to send to query parameters through form data but I am getting get request doesn't take form data. How to do it

enter image description here

http://ihub-fastapi-solubility.herokuapp.com/predict?solute=CC(C)(C)Br&solvent=CC(C)(C)O this is the URL and solute and solvent are the query parameters.

  const onSubmit = (e) => {
    e.preventDefault(); // <-- prevent the default form action

    const formData = new FormData();
    formData.set("solute", solutestate); // <-- local component state
    formData.set("solvent", solventstate); // <-- local component state
    console.log({ formData });

    fetch("http://ihub-fastapi-solubility.herokuapp.com/predict", {
      method: "get",
      body: formData,
    }).catch((err) => {
      setError(err.error);
      console.log(err);
    });

When I tried with post I got this error enter image description here

Phil
  • 157,677
  • 23
  • 242
  • 245
harsh
  • 435
  • 2
  • 6
  • 13
  • 1
    You can't send body with GET request, only with POST. Change the API so that it accepts and processes POST requests – ComixRu Feb 08 '22 at 01:52
  • 1
    @ComixRu I don't think OP _wants_ to send a POST request at all, they just want to capture their `FormData` params as query parameters – Phil Feb 08 '22 at 02:20
  • related: https://stackoverflow.com/q/61829691 – djvg Nov 03 '22 at 09:31

2 Answers2

4

FormData isn't the best choice here as that is primarily used in constructing multipart/form-data request payloads for use in POST, PUT and PATCH requests.

Use URLSearchParams instead to easily construct query parameters and serialise it into the URL...

const fetch = function fakeFetch(url, init) {
  console.log(init.method, url)
}

const solutestate = "CC(C)(C)Br"
const solventstate = "CC(C)(C)O"

const params = new URLSearchParams({
  solute: solutestate,
  solvent: solventstate
})

fetch(`http://ihub-fastapi-solubility.herokuapp.com/predict?${params}`, {
  method: "GET"
})

Using URLSearchParams has the added benefit of correctly URL encoding your data.

Phil
  • 157,677
  • 23
  • 242
  • 245
  • Also see [template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) for more about the `${}`. – djvg Nov 03 '22 at 09:18
2

In addition to @phil's answer: If you've got a form already, you can use FormData to initialize the URLSearchParams.

For example, if you've got a form like this

<form method="get" action="" id="form">
...
<input type="submit">
</form>

you can submit it as follows

const form = document.getElementById("form");
form.addEventListener("submit", submitForm);

function submitForm(event) {
  event.preventDefault();
  const url = form.action + "?" + new URLSearchParams(new FormData(form));
  fetch(url)...
}
djvg
  • 11,722
  • 5
  • 72
  • 103