#TIL
Long time no TIL! Worry not, I have been keeping up with coding, just haven’t been posting. Today’s TIL is my BugNote, aka, mistakes I’ve made in coding. I want to make a good practice of writing these BugNotes to prevent myself from repeating the same bugs.
Encountering issues and bugs during coding is inevitable in my opinion. That being said, I definitely don’t want to experience the frustration of REPEATing the same kind of bug across different projects. And what better way to prevent that than taking the time to at least write a short note of the mistakes I made?
So without further ado, let’s get to it.
BugNote 1 - Error messages can be a bit misleading
Sometimes error messages are helpful. Sometimes, they point you in a different direction. Or at least that is how it feels like for me. It might be because I’m not too well-versed with these errors yet.
Yesterday, I was in the process of building my youtube full-stack clone app. Part of what I worked on was building a client-side ‘add-comment’ functionality. What I wanted was for the client-side javascript to take the comment
text data and make a post fetch
to the back-end for the comment to be saved in MongoDB.
This was my client-side javascript making a fetch post request to my backend server.
//text data already pulled and put in variable called text
const response = await fetch(`/api/comment`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ text }),
});
Once the backend received this via req.body
, I was able to successfully save the comment data to my MongoDB. Now, originally, I had made the backend handler so that it simply sends a status code of 201
when the comment data was saved, like the code below:
// Original code to respond to request by sending 201 status:
return res.sendStatus(201);
But while following along with the Nomad Coder’s Wetube video course, Nicolas had talked about trying to send the MongoDB Comment document’s _id
back to the client-side. So, I updated my return statement below:
// Updated code to not only send status but return commentId to client-side
return res.sendStatus(201).json({ newCommentId: newComment._id });
Lo and behold, I realized about 15 minutes later that now, when I added a new comment to the video, the comment was added successfully to the database, but I also got this error response.
net::ERR_CONTENT_LENGTH_MISMATCH 201 Created
After doing some research on google and stackoverflow, I found advice similar to this:
The error is telling you that the content length set in the HTTP header(s) does not match the actual content length of the data on the wire. This is commonly caused by custom code that incorrectly sets the content-length header.
Look through the source code or try debugging. If you require debugging assistance, post all the relevant bits of your code base or enough code to reproduce the issue.
I was thoroughly confused because my fetch post request didn’t even do anything with the content-length
part of the header. I kept on searching for about 20+ minutes, to no avail.
And then after console logging different parts of my code, I realized that it was this return
statement that was causing the error. Upon more careful examination and review of my code as well as the video course, aha… I had realized that I made a typo/method mistake to my code.
// What I had coded initially:
return res.sendStatus(201).json({ newCommentId: newComment._id });
// What I should've changed the code into
return res.status(201).json({ newCommentId: newComment._id });
Something as simple as using res.sendStatus()
instead of changing it to res.status()
made such a difference. This bug also made me realize that sometimes, the error messages aren’t as helpful. I say this with a caveat that, this might have been mostly due to me not really understanding the meaning of this error message.
Bug Note 2 - importance of CODE order!
My next bugNote is regarding an issue that I had while completing yesterday’s coding challenge. In addition to submitting three ‘graduation projects’ over the course of the Nomad Coders - 10 week Web Basics Sprint, participants get a daily quiz or coding challenge pertinent to the assigned course/video of that day.
Yesterday, our coding challenge was to utilize MVC structure to create certain ‘Read’ functionality of CRUD using express, pug files, and JavaScript knowledge. We had to create a router and controller and view for the /
, /search
, and /:id
paths.
I had successfully created the views, as well as the routes and controllers for these three paths. I checked that the /:id
parameter paths and the index /
were rendering and loading properly.
Unfortunately, I was not so lucky with the /search
path. It kept saying that it couldn’t load the mixin pug template that I was using only for the /:id
view, so I was utterly confused. Looking back, if I were more analytical, I probably would’ve inferred the problem from this error statement. But yesterday’s me was so caught up in the immediate symptom/manifestation, which was - /SEARCH PATH NOT WORKING.
After about ~20 minutes of struggling to figure out the problem, it suddenly hit me to check my server.js
file.
router.get('/', home);
router.get('/:id', movie);
router.get('/search', search);
Ah.. I had mistakenly put the route involving the id parameter (/:id
) above the /search
path. This meant that my server thought that ‘server’ was also an id parameter. That’s why when I made a get request to /search
, the server was trying to render the view using the /:id
mixin template!
Two potential solutions for this issue:
- I could rearrange the order of the router.get() so that the get request for
/search/
is above the/:id
parameter route, like so:
router.get('/', home);
router.get('/search', search);
router.get('/:id', movie);
- I could utilize regular expression to specify the type of string that can be safely considered to be a parameter.
For instance, if I knew that all my id’s were 5-character-long, digit-only strings, I could specify that in my code:
router.get('/', home);
router.get('/:id([0-9]{5})', movie);
router.get('/search', search);
If I specify the allowable string structures for the id parameter, then the order of the router.get()
does not matter in this case.
Honestly, I prefer the first solution better because I’m not an expert in regular expression… But I also have a feeling I might forget to properly order these routers… I will report back if I have a strong preference on either of the solutions.
Tl;dr
- I make errors! I’m human so that’s perfectly okay, as long as I learn from them.
- Reminder that code order is important & that console.log() can be my friend.