I am in the process of adding a scoreboard to the 'Run, Boris Run' game I developed for my final project (see here) which involves saving a persons score to a database.
Today I came across a strange error where the variables I was sending across to the backend were coming back as 'undefined'.
Upon investigating further with some print statements, I found that my request didn't have a body at all (so strange!!!!!).
I couldn't seem to figure out why my body was undefined and after some googling I came across something I had used before...
It seems I needed to import and use the Express Middleware body-parser. And this is a lovely explanation from Stack Overflow as to how it works:
body-parser extracts the entire body portion of an incoming request stream and exposes it on req.body as something easier to interface with. You don't need it per se, because you could do all of that yourself. However, it will most likely do what you want and save you the trouble.
In particular, I needed to make use of the bodyparser.json() method which parses the request data as JSON and exposes the resulting object on req.body.
I think it's a bit safe to say I took body parser for granted but I won't be forgetting it again anytime soon! This is also a lesson learned about making sure you understand what every imported library is doing and why you require it.
P.s. Here is the stack overflow explanation if you are interested.
Top comments (0)