I’ve been working on the URL Shortener Microservice the past few days, and it seems like everything is working in the post handler except for the req.body part that I grab in the handler. The req.body is always an empty object {}.
I’m using the app.use(bodyParser.urlencoded({extended: false})) (look below) that we learned in the tutorials to parse the body. However, I’ve also tried the bodyParser.json(), and req.body is still an empty object {}.
Can someone help?
Here’s the part of my post handler that’s giving me issues:
Here’s the bodyParser I’m using as mentioned above:
Yes, express is the back-end.
I just tried including express.json() in the middleware, but it gave me an error of “Unexpected token u in JSON at position 0”
If I use express.json() or bodyParser.json() it gives me the error above.
If I use the bodyParser.urlencoded() then no matter the value of extended, I still get an empty object {} for the request body
The issue was that I saved the post data to send as querystring.stringify when it needed to be JSON.stringify since the bodyParser.json() couldn’t reconcile the querystring object.
Here is how my code looked originally when it wasn’t working:
This is how it currently looks now that it’s working:
Basically, the post data format and the bodyParser format have to be the same in order for the bodyParser to correctly parse it. I overlooked this and that was the cause of my errors.