DEV Community


Posted on


POST FormData to JSON object array with ReacStrap Form and Express

I'm currently learning the MERN stack and I'm very new to React and Express. My current task is to use an API I previously created and update the JSON data using React.

I created a form component using ReactStrap and now I need POST that data to the JSON object…

Top comments (2)

techfortified profile image
Peter Kelvin Torver

When you create an instance of FormData you need to append data to the formData object. I have seen your issue on Stack overflow.
Use this solution

const data = new FormData()
data.append("username", username)

// Go ahead and append all your variables
Enter fullscreen mode Exit fullscreen mode

On your Nodejs server, if you're not sending a file along with your form, do not send form data content-type to the server. Use json instead

jamesthomson profile image
James Thomson

The reason you get the error

Uncaught TypeError: Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.

is because the parameter it expects is a form element.

I can see you have const form = useRef(null);, but I can't see anywhere that you actually set that reference to your form. You need to use forwardRef in your WebForm component to target the form.

This way you can them put a ref on your component to gain access to the form element nested within it. Assuming you've forwarded the ref, you can then write <WebForm ref={form} ... /> which should then ensure your submit function gets all the form data when submitting to your endpoint.