URL Shortener Microservice: Req.body is empty {}


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:

Finally, here’s my post request code:

Mind posting your code instead of a screenshot?
You can pet the cat if you do >>> :cat2:

You got it:

Try setting the extended option to true.

I tried that before and still didn’t work :confused:

Post method starts at line 216 btw

In your back-end are you using express?
Did you include express.json( ) in the middleware?

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

You might have to print screen your express setup.

Here is my project if you want to look at my setup:

Look at comment above for new project link^

I cleaned up the code so it only has to deal with my current project


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.

Thanks for all your help, everyone!

1 Like