Using fetch to send form data to server.js - the body object is empty

Hello. I’m building a simple visitors’ book, using React on the front-end, and the back-end is sending the data to a MongoDB/Mongoose database.

I started with the ~starter-react set-up, and took it from there.

It seems to work okay with action/method in the form element - all the form data arrives and goes into the database - but I’m now trying to handle the POST in the handleSubmit(event) method. I’ve cobbled together something from Google searches, which uses ‘fetch’. When I console.log the server.js file, the body is empty. I’m clearly a beginner, and I don’t understand everything that’s going on!

My project is here

Hi :slight_smile:

you are sending the body content as json, so you have to tell the body-parser module on the backend to parse json. Add this line right after the line in which you set up the urlencoded parser:


Et voila’ :slight_smile:

Thanks for replying. I’ve tried that, but console.log throws up the following error!

SyntaxError: Unexpected token o in JSON at position 1

3:30 PM

at JSON.parse (<anonymous>)

3:30 PM

at parse (/rbd/pnpm-volume/9d9d2291-a5d7-41ee-bb0c-1c8de6e85fa4/node_modules/

3:30 PM

at /rbd/pnpm-volume/9d9d2291-a5d7-41ee-bb0c-1c8de6e85fa4/node_modules/

3:30 PM

at invokeCallback (/rbd/pnpm-volume/9d9d2291-a5d7-41ee-bb0c-1c8de6e85fa4/node_modules/

3:30 PM

at done (/rbd/pnpm-volume/9d9d2291-a5d7-41ee-bb0c-1c8de6e85fa4/node_modules/

3:30 PM

at IncomingMessage.onEnd (/rbd/pnpm-volume/9d9d2291-a5d7-41ee-bb0c-1c8de6e85fa4/node_modules/

3:30 PM

at emitNone (events.js:106:13)

3:30 PM

at IncomingMessage.emit (events.js:208:7)

3:30 PM

at endReadableNT (_stream_readable.js:1064:12)

3:30 PM

at _combinedTickCallback (internal/process/next_tick.js:139:11)

3:30 PM

at process._tickCallback (internal/process/next_tick.js:181:9)

Does it throw this error when you try to POST on the /database endpoint?

ok, found the issue: You’ve to wrap the body in app.jsx in JSON.stringify:

body: JSON.stringify({ dummy_key: "dummy_value" })
1 Like

You got it! It’s working. Thanks a lot.