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

142 views Asked by At

I/ve made a form with formik on my portfolio (https://alexpowelldev.com/)that im trying to send the data being submitted to getform.io. For some reason I'm getting a 400 error in the console when submitting which is as folllows:

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

POST https://getform.io/f/... 400 onSubmit @ ContactMe.js:27 ContactMe.js:33 Response {type: 'cors', url: 'https://getform.io/f/...', redirected: false, status: 400, ok: false, …}

There seems to be some sort of disconnect. Here is the code:

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

Any help would be much appreciated.I can add more context if needed.

edit* I found in the chrome dev tools this message: enter image description here

However you can see in my initialValues for formik that They all have unique names.

1

There are 1 answers

2
Phil On BEST ANSWER

From a very quick look at the examples on the https://getform.io/ home page, it appears they expect request bodies in multipart/form-data format.

To provide this, create a FormData instance and add your form values

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

Looking further, they also support application/x-www-form-urlencoded...

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

and even application/json

fetch("https://getform.io/f/...", {
  method: "POST",
  headers: {
    accept: "application/json",
    "content-type": "application/json",
  },
  body: JSON.stringify(values),
})