【问题标题】:How to send form data through get request in fetch api如何通过 fetch api 中的 get 请求发送表单数据
【发布时间】:2022-02-08 10:15:06
【问题描述】:

我有一个 API,我在其中调用 get 请求以通过表单数据发送到查询参数,但我得到的 get 请求不接受表单数据。怎么做

http://ihub-fastapi-solubility.herokuapp.com/predict?solute=CC(C)(C)Br&solvent=CC(C)(C)O 这是 URL,solute 和solvent 是查询参数。

  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);
    });

当我尝试使用 post 时,我收到了这个错误

【问题讨论】:

  • 您不能使用 GET 请求发送正文,只能使用 POST。更改 API 以使其接受和处理 POST 请求
  • @ComixRu 我不认为 OP 想要 发送 POST 请求,他们只是想捕获他们的 FormData 参数作为查询参数

标签: javascript reactjs post fetch-api


【解决方案1】:

FormData 不是这里的最佳选择,因为它主要用于构造multipart/form-data 请求有效负载以用于POSTPUTPATCH 请求。

改用URLSearchParams 来轻松构造查询参数并将其序列化到 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"
})

使用URLSearchParams 具有正确URL encoding 数据的额外好处。

【讨论】:

    猜你喜欢
    • 2016-04-05
    • 2016-07-19
    • 1970-01-01
    • 2019-12-11
    • 1970-01-01
    • 2016-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多