How to fetch the POST method with formik using getform.io

问题描述 投票:0回答:1

我/已经在我的投资组合中用 formik 制作了一个表格 (https://alexpowelldev.com/),我试图将提交的数据发送到 getform.io。 出于某种原因,我在提交时在控制台中收到 400 错误,如下所示:

 form data {firstName: 'Alexander', email: '[email protected]', type: '', comment: 'test kjdfhsdkjfhakjsdfhisafbsdivuabvierbuib'}ContactMe.js:27 
     

发布https://getform.io/f/..。 400 onSubmit @ ContactMe.js:27 ContactMe.js:33 响应 {type: 'cors', url: 'https://getform.io/f/...', redirected: false, status: 400, ok: false, ...}

似乎有某种脱节。这是代码:

const formik = useFormik({
initialValues: {firstName:"",email:"",type:"",comment:"" },
onSubmit: (values) => {
  fetch("https://getform.io/f/...", {
    method: "POST",
    body: values,
    headers: {
        "Accept": "application/json",
    },
})
.then(response => console.log(response))
.catch(error => console.log(error))
  console.log('form data', values)
}

 <form 
       onSubmit={formik.handleSubmit}
       >

任何帮助将不胜感激。如果需要,我可以添加更多上下文。

edit* 我在 chrome 开发工具中发现了这条消息:

但是您可以在我的 formik 初始值中看到它们都有唯一的名称。

reactjs post fetch-api formik getform
1个回答
0
投票

快速浏览 https://getform.io/ 主页上的示例,他们似乎希望请求主体采用

multipart/form-data
格式。

为此,创建一个 FormData 实例并添加您的表单值

onSubmit: async (values) => {
  const body = new FormData();
  Object.entries(values).forEach(([ key, val ]) => {
    body.append(key, val);
  });

  const res = await fetch("https://getform.io/f/...", {
    method: "POST",
    headers: { accept: "application/json" },
    body,
  });

  if (!res.ok) {
    console.error(res.status, await res.text());
  } else {
    console.log(await res.json());
  }
}

再往前看,他们也支持

application/x-www-form-urlencoded
...

fetch("https://getform.io/f/...", {
  method: "POST",
  headers: { accept: "application/json" },
  body: new URLSearchParams(values),
})

甚至

application/json

fetch("https://getform.io/f/...", {
  method: "POST",
  headers: {
    accept: "application/json",
    "content-type": "application/json",
  },
  body: JSON.stringify(values),
})
© www.soinside.com 2019 - 2024. All rights reserved.