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!
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:
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/.registry.npmjs.org/body-parser/1.18.3/node_modules/body-parser/lib/types/json.js:89:19)
3:30 PM
at /rbd/pnpm-volume/9d9d2291-a5d7-41ee-bb0c-1c8de6e85fa4/node_modules/.registry.npmjs.org/body-parser/1.18.3/node_modules/body-parser/lib/read.js:121:18
3:30 PM
at invokeCallback (/rbd/pnpm-volume/9d9d2291-a5d7-41ee-bb0c-1c8de6e85fa4/node_modules/.registry.npmjs.org/raw-body/2.3.3/node_modules/raw-body/index.js:224:16)
3:30 PM
at done (/rbd/pnpm-volume/9d9d2291-a5d7-41ee-bb0c-1c8de6e85fa4/node_modules/.registry.npmjs.org/raw-body/2.3.3/node_modules/raw-body/index.js:213:7)
3:30 PM
at IncomingMessage.onEnd (/rbd/pnpm-volume/9d9d2291-a5d7-41ee-bb0c-1c8de6e85fa4/node_modules/.registry.npmjs.org/raw-body/2.3.3/node_modules/raw-body/index.js:273:7)
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)