Sheffield | 25-SDC-Nov | Sheida Shabankari | Sprint 3 |Middleware exercises#64
Sheffield | 25-SDC-Nov | Sheida Shabankari | Sprint 3 |Middleware exercises#64sheida-shab wants to merge 1 commit intoCodeYourFuture:mainfrom
Conversation
OracPrime
left a comment
There was a problem hiding this comment.
Two comments to understand. Don't bother fixing the bug unless you fancy the stretch objective. Otherwise solid code.
| //Middleware #۱: | ||
| app.use((req,res,next)=>{ | ||
| const usernameHeader=req.headers["x-username"]; | ||
| req.username=usernameHeader ? usernameHeader : null; |
There was a problem hiding this comment.
This works, but would more often be seen as
req.username = usernameHeader ?? null;
or
req.username = usernameHeader || null;
An interesting exercise is to understand the difference between these two and why the first is better.
There was a problem hiding this comment.
Thanks for the feedback! That was a really useful point — understanding the difference between || and ?? helped me learn a practical new detail about handling defaults more safely
| app.use((req,res,next)=>{ | ||
| let data=''; | ||
| req.on('data',chunk => { | ||
| data+=chunk; |
There was a problem hiding this comment.
There is a subtle bug here. chunk is bytes, not a string. data+=chunk will do a convert to string. In UTF8 a single character can be as many as 4 bytes (even though most are 1). If the chunk happens to end in the middle of a long character, the conversion to string will go wrong. You're saving concatenating all the bytes first and then converting to string afterwards. It's probably out of scope for this exercise though.
There was a problem hiding this comment.
Thanks for pointing that out — I wasn’t aware of the UTF-8 edge case with chunks. That’s a really useful detail to learn, even if it’s out of scope for this exercise.
Description:
This PR adds two directories for the middleware exercises:
middleware-custom/ – Express app with two custom middlewares: reading X-Username header and parsing/validating JSON array POST body.
middleware-express-json/ – Same app using Express’s built-in express.json() middleware instead of custom body parsing.
Both apps have a POST endpoint returning authentication status and requested subjects.